Wednesday, 30 December 2015

ServletConfig example to get initialization parameter from web.xml



import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class First
 */
@WebServlet("/First")
public class First extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   
   ServletConfig config=getServletConfig();
   String driver=config.getInitParameter("driver");
   out.print("Driver is: "+driver);
       
   out.close();


}

}


Web.xml
<web-app>  
  
<servlet>  
<servlet-name>First</servlet-name>  
<servlet-class>First</servlet-class>  
  
<init-param>  
<param-name>driver</param-name>  
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>  
</init-param>  
  
</servlet>  
  
<servlet-mapping>  
<servlet-name>First</servlet-name>  
<url-pattern>/servlet1</url-pattern>  
</servlet-mapping>  
  
</web-app>  

Output:-

No comments:

Post a Comment