Wednesday, August 7, 2013

About Servlet Init Parameters and Context Init Parameters.

What is difference between servlet init parameters and Context init parameters ?

1)Servlet init parameters are declared as following in <servlet> tag section.
These can be seen only by LoginServlet, no other servlet or jsp page can
use these.



<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>myservlets.LoginServlet</servlet-class>
<init-param>
<param-name>unknownuser</param-name>
<param-value>We are not able to find your details in our database Modified.</param-value>
</init-param>
</servlet>

2)Context init parameters are declared in <context-param> section.
These are declared as following in web.xml.

<context-param>
<description>Testing Context parameters
</description>
<param-name>contextemail</param-name>
<param-value>context@gmail.com</param-value>
</context-param>

Context parameters can be read by all the servlets and jsp pages..
where as servlet init parameters are specific to that servlet and can't
be shared by others servlets or jsp pages.

Most Imp Things:
---------------------

3)For every servlet there is one servletConfig object created by container

4)There is only one ServletContext Object per web application..

5) If you have 5 servlets that means container creates 5 ServletConfig objects
but it creates only one ServletContext Object.

6)Servlet init params are read in servlet with following code.

getServletConfig().getInitParameter("unknownuser");

7)Context init parameters are read in servlet with following code

System.out.println(getServletContext().getInitParameter("contextemail"));

In jsp you can read context init parameters with following syntax..
Refer parameterReader.jsp which reads context init parameters.

<%
out.println(application.getInitParameter("contextemail"));
%>

In jsp page ServletContext is referred as application.Please remember this.

I am uploading the HelloWorld with Initialization parameters and context
initalization parameters..



<?xml version="1.0" encoding="UTF-8"?>

<!--
Document : web.xml
Created on : July 31, 2013, 12:50 AM
Author : Rishitha
Description:
Purpose of the document follows.
-->

<web-app>
<context-param>
<description>Testing Context parameters
</description>
<param-name>contextemail</param-name>
<param-value>context@gmail.com</param-value>
</context-param>

<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>myservlets.LoginServlet</servlet-class>
<init-param>
<param-name>unknownuser</param-name>
<param-value>We are not able to find your details in our database Modified.</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>

</web-app>

No comments:

Post a Comment