How to get Context Init Parameters and Servlet Init Parameters from web.xml file


If you want to define init parameters for your project use the following example;

First create a web.xml file;

<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app version=”3.0″ xmlns=”http://java.sun.com/xml/ns/javaee&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd”&gt;
    <context-param>
        <param-name>contextParameter1</param-name>
        <param-value>from web.xml file contextParameter1 value</param-value>
    </context-param>
    <context-param>
        <param-name>contextParameter2</param-name>
        <param-value>from web.xml contextParameter2 value</param-value>
    </context-param>
    <servlet>
        <servlet-name>TestServlet</servlet-name>
        <jsp-file>/index.jsp</jsp-file>
        <init-param>
            <param-name>jspFileInitParameter1</param-name>
            <param-value>from web.xml servletParameter1 value</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>TestServlet</servlet-name>
        <url-pattern>/index.jsp</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

And create a index.jsp file

<%–
    Document   : index
    Created on : 17.Jun.2011, 00:10:54
    Author     : tunatore
–%>

<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<!DOCTYPE html>
<html>
    <head>
     <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
        <title>Getting WEB.XML init parameters</title>
    </head>
<body>
        <b>Context init parameters</b> </br></br>
        Context init parameter access : value –>
        <font color=”GREEN”><%= application.getInitParameter(“contextParameter1”) %></font> </br></br>
        Context init parameter access : value –>
        <font color=”GREEN”><%= application.getInitParameter(“contextParameter2”) %></font> </br></br>
        <b>Servlet init parameter</b> </br></br>

        Servlet init (JSP) parameter access : value –> <font color=”GREEN”>
<%= pageContext.getServletConfig().getInitParameter(“jspFileInitParameter1”) %></font>

    </body>
</html>

Example output;


Download Source

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s