ServletContext in Java
Using ServletContext in Java Servlets
ServletsHome
ServletContext in Java
Used to set web application level variables.
ServletContext is an interface which helps us to communicate with the
servlet container. There is only one ServletContext for the entire web
application, and the components of the web application can share it. ex: site email, site language, currency, contact number, date format. etc.
In web.xml
<context-param>
<param-name>Email</param-name>
<param-value>admin@example.com</param-value>
</context-param>
This Email value can be accessed by any servlet within the context. In the servlet code, we will write this as..
ServletContext context = getServletContext();
pw.println(context.getInitParameter("Email");
ContextParamServlet.java
package codingzon;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ContextParamServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();
ServletContext context = getServletContext();
pw.println("<br>Email = " + context.getInitParameter("Email"));
pw.println("<br>Country = " + getServletContext().getInitParameter("Country"));
pw.println("<br>Currency = " + getServletContext().getInitParameter("Currency"));
}
}
in web.xml declare parameters as shown below in <web-app> tag
...
<context-param>
<param-name>Email</param-name>
<param-value>admin@example.net</param-value>
</context-param>
<context-param>
<param-name>Country</param-name>
<param-value>India</param-value>
</context-param>
<context-param>
<param-name>Currency</param-name>
<param-value>Rupee</param-value>
</context-param>
...
</web-app>
Output:
Comments
Post a Comment