Wednesday, 30 December 2015

ServletContext example to get the initialization parameter from web.xml file



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

import javax.servlet.ServletContext;
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 pw = response.getWriter();
ServletContext context=getServletContext();
String drivername = context.getInitParameter("dname");
pw.println("Driver Name is" +drivername);
pw.close();
}

}


web.xml
<web-app>  
  
<servlet>  
<servlet-name>First</servlet-name>  
<servlet-class>First</servlet-class>  
</servlet>  
  
<context-param>  
<param-name>dname</param-name>  
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>  
</context-param>  
  
<servlet-mapping>  
<servlet-name>First</servlet-name>  
<url-pattern>/context</url-pattern>  
</servlet-mapping>  
  
</web-app>  

Output:-

No comments:

Post a Comment