JSP Impilicit Objects - config


JSP config -

config is an object of javax.servlet.ServletConfig. In servlet we can get it by using getServletConfig() method, whereas in JSP it is automatically availabel.

Example -

This example will show you how we can access initialization parameters from web.xml in JSP file using config object.

1- index.html or index.jsp - This will be your default page.
Make the following changes in index page -
<!DOCTYPE html>
<html>
    <head>
        <title>JSP config Demo</title>
    </head>
    <body>
        <a href="First">Show Init Parameters</a> 
    </body>
</html>        

2- web.xml - Here we will create a JSP file named First. In web.xml we are passing initialization parameters with JSP file definition, which we will access in First JSP file using config -

<web-app>
    <servlet>
        <servlet-name>MyFirstJSP</servlet-name>
        <jsp-file>/First.jsp</jsp-file>
        
        <init-param>
            <param-name>name</param-name>
            <param-value>Rohit</param-value>
        </init-param>
        <init-param>
            <param-name>email</param-name>
            <param-value>rohit@gettechnotes.com</param-value>
        </init-param>
        
    </servlet>
    <servlet-mapping>
        <servlet-name>MyFirstJSP</servlet-name>
        <url-pattern>/First</url-pattern>
    </servlet-mapping>
</web-app>    
        

3- Create a JSP file named First, where we will access the initialization parameters defined in web.xml -
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%
        String name = config.getInitParameter("name");
        String email = config.getInitParameter("email");
        out.println("Name - "+name);
        out.println("<br>");
        out.println("Email - "+email);  
        %>
    </body>
</html>        

4- Now run the project and it will show you the index page -



Click on the link and it will show you the initialization parameters we specify in web.xml -



Download this example (NetBeans implementation) - Click Here