Wednesday, July 27, 2016

Reading Initialization parameters.

Reading Initialization parameters:

Syntax to provide the initialization parameter for a servlet

The init-param sub-element of servlet is used to specify the initialization parameter for a servlet.
  1. <web-app>  
  2.   <servlet>  
  3.     ......  
  4.       
  5.     <init-param>  
  6.       <param-name>parametername</param-name>  
  7.       <param-value>parametervalue</param-value>  
  8.     </init-param>  
  9.     ......  
  10.   </servlet>  
  11. </web-app>  


ServletConfig to get initialization parameter

In this example, we are getting the one initialization parameter from the web.xml file and printing this information in the servlet.

DemoServletInit.java
  1. import java.io.*;  
  2. import javax.servlet.*;  
  3. import javax.servlet.http.*;  
  4.   
  5. public class DemoServletInit extends HttpServlet {  
  6. public void doGet(HttpServletRequest request, HttpServletResponse response)  
  7.     throws ServletException, IOException {  
  8.   
  9.     response.setContentType("text/html");  
  10.     PrintWriter PW = response.getWriter();  
  11.       
  12.     ServletConfig config=getServletConfig();  
  13.     String name=config.getInitParameter("name");  
  14.     pw.print("Name is: "+driver);  
  15.           
  16.     pw.close();  
  17.     }  
  18.   
  19. }  
  20. Here web.xml is updated as following

<servlet>
    <servlet-name>D</servlet-name>
    <servlet-class>DemoServletInit</servlet-class>
<init-param>  
<param-name>name</param-name>  
<param-value>DiyaShirley</param-value>  
</init-param>  

</servlet>

<servlet-mapping>
    <servlet-name>D</servlet-name>
    <url-pattern>/Demo</url-pattern>
</servlet-mapping>

  1. after executing output displays like following:








Labels:

5 Comments:

At February 14, 2019 at 1:47 PM , Blogger Unknown said...

Ghjjkkk

 
At April 15, 2019 at 10:36 AM , Blogger Unknown said...

Iam getting Null as output

 
At April 18, 2019 at 6:35 AM , Blogger User said...

What is the driver in this case ?

 
At May 7, 2019 at 2:13 AM , Blogger K V Sri Harsha said...

Just use pw.print("Name is:"+name);
That should fix this.

 
At May 7, 2019 at 4:11 PM , Blogger Unknown said...

Thanks for this!

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home