index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 | <!DOCTYPE html> <html> <head> <title>Servlet Context Example</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <h3>Servlet Context Example</h3> <a href="get-servlet-context">Call Servlet1</a> <a href="get-context">Call Servlet2</a> </body> </html> |
web.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <?xml version="1.0" encoding="UTF-8"?> <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"> <context-param> <param-name>SiteName</param-name> <param-value>Ebhor.com</param-value> </context-param> <servlet> <servlet-name>ServletContext</servlet-name> <servlet-class>ebhor.servlet.ServletContext</servlet-class> </servlet> <servlet> <servlet-name>ServletContext1</servlet-name> <servlet-class>ebhor.servlet.ServletContext1</servlet-class> </servlet> <servlet-mapping> <servlet-name>ServletContext</servlet-name> <url-pattern>/get-servlet-context</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ServletContext1</servlet-name> <url-pattern>/get-context</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> </web-app> |
ServletContext.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | package ebhor.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ServletContext extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String value=getServletContext().getInitParameter("SiteName"); PrintWriter out=response.getWriter(); out.println("At ServletContext servlet "); out.println("<h2>Site Name is "+value+"</h2>"); } } |
ServletContext1.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | package ebhor.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ServletContext1 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String value = getServletContext().getInitParameter("SiteName"); PrintWriter out = response.getWriter(); out.println("At ServletContext1 servlet "); out.println("<h2>Site Name is " + value + "</h2>"); } } |
Results