Professional Documents
Culture Documents
Java Ii Unit
Java Ii Unit
An object of ServletContext is created by the web container at time of deploying the project. This object can be used to get
configuration information from web.xml file. There is only one ServletContext object per web application.
If any information is shared to many servlet, it is better to provide it from the web.xml file using the <context-param> element.
Advantage of ServletContext
Easy to maintain if any information is shared to all the servlet, it is better to make it available for all the servlet. We
provide this information from the web.xml file, so if the information is changed, we don't need to modify the servlet. Thus
it removes maintenance problem.
1. The object of ServletContext provides an interface between the container and servlet.
2. The ServletContext object can be used to get configuration information from the web.xml file.
3. The ServletContext object can be used to set, get or remove attribute from the web.xml file.
4. The ServletContext object can be used to provide inter-application communication.
1. public String getInitParameter(String name):Returns the parameter value for the specified parameter name.
2. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters.
3. public void setAttribute(String name,Object object):sets the given object in the application scope.
4. public Object getAttribute(String name):Returns the attribute for the specified name.
5. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters as an
Enumeration of String objects.
6. public void removeAttribute(String name):Removes the attribute with the given name from the servlet context.
<web-app>
......
<context-param>
<param-name>parametername</param-name>
<param-value>parametervalue</param-value>
</context-param>
......
</web-app>
DemoServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
pw.close();
}}
web.xml
<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping>
</web-app>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
ServletContext context=getServletContext();
Enumeration<String> e=context.getInitParameterNames();
String str="";
while(e.hasMoreElements()){
str=e.nextElement();
out.print("<br> "+context.getInitParameter(str));
}
}}
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6. </servlet>
7.
8. <context-param>
9. <param-name>dname</param-name>
10. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
11. </context-param>
12.
13. <servlet-mapping>
14. <servlet-name>sonoojaiswal</servlet-name>
15. <url-pattern>/context</url-pattern>
16. </servlet-mapping>
17.
18. </web-app>
DemoServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
ServletContext context=getServletContext();
Enumeration<String> e=context.getInitParameterNames();
String str="";
while(e.hasMoreElements()){
str=e.nextElement();
out.print("<br> "+context.getInitParameter(str));
}
}}
web.xml
<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
<context-param>
<param-name>username</param-name>
<param-value>system</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>oracle</param-value>
</context-param>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping>
</web-app>
Or
RequestDispatcher dispatcher =
req.getRequestDispatcher("/index.html");
dispatcher.forward(req, res);
response.sendRedirect
("http://localhost:8080/Test/ServletTwo");
index.html
<form action="servlet1" method="post"\>
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"><br/>
<input type="submit" value="login"/>
</form>
login.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("userName");
String pass=request.getParameter("userPass");
if(pass.equals("servlet"){
RequestDispatcher dispatcher=request.getRequestDispatcher("servlet2");
dispatcher.forward(request, response);
}
else{
out.print("Either UserName or Password is Wrong!");
RequestDispatcher dispatcher=request.getRequestDispatcher("/index.html");
dispatcher.include(request, response);
}
}
HomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HomeServlet extends HttpServlet {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("userName");
out.print("HomePage "+name);
}
web.xml
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>HomeServlet</servlet-name>
<servlet-class>HomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping\>
<servlet-name>HomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Events are basically occurrence of something. Changing the state of an object is known as an event.
We can perform some important tasks at the occurrence of these exceptions, such as counting total and current logged-in users, creating
tables of the database at time of deploying the project, creating database connection object etc.
There are many Event classes and Listener interfaces in the javax.servlet and javax.servlet.http packages.
Event classes
The event classes are as follows:
1. ServletRequestEvent
2. ServletContextEvent
3. ServletRequestAttributeEvent
4. ServletContextAttributeEvent
5. HttpSessionEvent
6. HttpSessionBindingEvent
Event interfaces
The event interfaces are as follows:
1. ServletRequestListener
2. ServletRequestAttributeListener
3. ServletContextListener
4. ServletContextAttributeListener
5. HttpSessionListener
6. HttpSessionAttributeListener
7. HttpSessionBindingListener
8. HttpSessionActivationListener
Interface for receiving notifications about requests entering and exiting a web
javax.servlet.ServletRequestListener application’s scope.
istener Interface Description
<listener>
<listener-class>Name of the Listener class</listener-class>
</listener>
……
</web-app>
Except for HttpSessionBindingListener and HttpSessionActivationListener, all Listeners require the aforementioned
listener configuration.
Methods for Event Listeners and Related Classes
1) Methods for ServletContextListeners and the ServletContextEvent Class
The following methods are defined by ServletContextListener:
Methods Description
void contextInitialized(ServletContextEvent This function is used to inform the listener that the servlet context has been formed
sce) and that the application is now ready to handle requests.
void contextDestroyed(ServletContextEvent
sce) This function is used to alert the listener that the program is about to be terminated.
When a web application is deployed on the server, the ServletContextEvent is informed. It includes the technique
shown below, which your listener might call:
ServletContext getServletContext(): This method retrieves the servlet context object that was created or is going to be
deleted, from which you may get any information you want.
2) Methods for ServletContextAttributeListener and the ServletContextAttributeEvent Class
ServletContextAttributeListener specifies the following methods:
When a web application is deployed on the server, the ServletContextEvent is informed. It includes the technique
shown below, which your listener might call:
ServletContext getServletContext(): This method retrieves the servlet context object that was created or is going to be
deleted, from which you may get any information you want.
2) Methods for ServletContextAttributeListener and the ServletContextAttributeEvent Class
ServletContextAttributeListener specifies the following methods:
Methods Description
It’s used to inform the listener that the servlet context has been updated
void attributeAdded(ServletContextAttributeEvent scae): with an attribute.
void attributeRemoved(ServletContextAttributeEvent It’s used to inform the listener that an attribute from the servlet context has
scae): been deleted.
void attributeReplaced(ServletContextAttributeEvent It’s used to inform the listener when an attribute in the servlet context has
scae) been replaced.
The event class ServletContextAttributeEvent is used to notify about changes to the attributes of a web application’s
servlet context. It includes the techniques listed below, which your listener can use:
1. String getName() returns the name of the attribute that was added, deleted, or replaced as a
2. string.
3. Object getValue() is a method for retrieving the value of an attribute that has been added, deleted, or replaced.
This method returns the previous value, not the new value, in the event of a replaced attribute.
3) Methods for HttpSessionListeners and the HttpSessionEvent Class
HttpSessionListener specifies the following methods
Methods Description
void sessionCreated(HttpSessionEvent hse) It’s used to inform the listener that a session has been established.
void sessionDestroyed(HttpSessionEvent hse): It’s used to let the listener know that a session has been terminated.
When the session object is modified, HttpSessionEvent is informed. It includes the technique shown below, which your
listener might call:
HttpSession getSession(): This function is used to obtain the generated or deleted session object.
4) Methods for HttpSessionAttributeListener and the HttpSessionBindingEvent Class
HttpSessionAttributeListener specifies the following methods:
Methods Description Methods Description
AppContextAttributeListener.java
• Java
package com.geeksforgeeks.listener;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.annotation.WebListener;
@WebListener
implements ServletContextAttributeListener {
public void
attributeAdded(ServletContextAttributeEvent
servletContextAttributeEvent)
System.out.println(
+ servletContextAttributeEvent.getName() + ","
+ servletContextAttributeEvent.getValue()
+ "}");
public void
attributeReplaced(ServletContextAttributeEvent
servletContextAttributeEvent)
System.out.println(
+ servletContextAttributeEvent.getName() + ","
+ servletContextAttributeEvent.getValue()
+ "}");
public void
attributeRemoved(ServletContextAttributeEvent
servletContextAttributeEvent)
System.out.println(
"ServletContext attribute removed::{"
+ servletContextAttributeEvent.getName() + ","
+ servletContextAttributeEvent.getValue()
+ "}");
AppContextListener.java
• Java
package com.geeksforgeeks.listener;
import com.geeksforgeeks.db.*;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
implements ServletContextListener {
ServletContextEvent servletContextEvent)
ServletContext ctx
= servletContextEvent.getServletContext();
String u = ctx.getInitParameter("DBUSER");
String p = ctx.getInitParameter("DBPWD");
DatabaseManager dbManager
ctx.setAttribute("DBManager", dbManager);
System.out.println(
ServletContextEvent servletContextEvent)
{
ServletContext ctx
= servletContextEvent.getServletContext();
DatabaseManager dbManager
= (DatabaseManager)ctx.getAttribute(
"DBManager");
dbManager.closeConnection();
System.out.println(
MyServletRequestListener.java
• Java
package com.geeksforgeeks.listener;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
@WebListener
implements ServletRequestListener {
ServletRequestEvent servletRequestEvent)
ServletRequest servletRequest
= servletRequestEvent.getServletRequest();
System.out.println(
+ servletRequest.getRemoteAddr());
ServletRequestEvent servletRequestEvent)
ServletRequest servletRequest
= servletRequestEvent.getServletRequest();
System.out.println(
+ servletRequest.getRemoteAddr());
}
MySessionListener.java
• Java
package com.geeksforgeeks.listener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
@WebListener
implements HttpSessionListener {
public void
sessionCreated(HttpSessionEvent sessionEvent)
{
System.out.println(
+ sessionEvent.getSession().getId());
public void
sessionDestroyed(HttpSessionEvent sessionEvent)
System.out.println(
+ sessionEvent.getSession().getId());
MyServlet.java
• Java
package com.geeksforgeeks.servlet;
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;
import javax.servlet.http.HttpSession;
@WebServlet("/MyServlet")
HttpServletResponse response)
ctx.setAttribute("User", "GeeksForGeeks");
ctx.removeAttribute("User");
Output:
When we deploy our application and access MyServlet, the server log file will include the following logs.
In the browser, we’ll see something like this.
Servlet Filter
A filter is an object that is invoked at the preprocessing and postprocessing of a request.
It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption and decryption, input validation etc.
The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we remove the entry of filter from the web.xml file, filter will
be removed automatically and we don't need to change the servlet.
Usage of Filter
o recording all incoming requests
o logs the IP addresses of the computers from which the requests originate
o conversion
o data compression
o encryption and decryption
o input validation etc.
Advantage of Filter
1. Filter is pluggable.
2. One filter don't have dependency onto another resource.
3. Less Maintenance
Filter API
Like servlet filter have its own API. The javax.servlet package contains the three interfaces of Filter API.
1. Filter
2. FilterChain
3. FilterConfig
1) Filter interface
For creating any filter, you must implement the Filter interface. Filter interface provides the life cycle methods for a filter.
Method Description
public void init(FilterConfig config) init() method is invoked only once. It is used to initialize the filter.
public void doFilter(HttpServletRequest doFilter() method is invoked every time when user request to any
request,HttpServletResponse response, FilterChain chain) resource, to which the filter is mapped.It is used to perform filtering
tasks.
public void destroy() This is invoked only once when filter is taken out of the service.
2) FilterChain interface
The object of FilterChain is responsible to invoke the next filter or resource in the chain.This object is passed in the doFilter method of
Filter interface.The FilterChain interface contains only one method:
1. public void doFilter(HttpServletRequest request, HttpServletResponse response): it passes the control to the next filter or resource.
<web-app>
<filter>
<filter-name>...</filter-name>
<filter-class>...</filter-class>
</filter>
<filter-mapping>
<filter-name>...</filter-name>
<url-pattern>...</url-pattern>
</filter-mapping>
</web-app>
For mapping filter we can use, either url-pattern or servlet-name. The url-pattern elements has an advantage over servlet-name element
i.e. it can be applied on servlet, JSP or HTML.
index.html
<a href="servlet1">click here</a>
MyFilter.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
PrintWriter out=resp.getWriter();
out.print("filter is invoked before");
import javax.servlet.ServletException;
import javax.servlet.http.*;
out.print("<br>welcome to servlet<br>");
}
web.xml
For defining the filter, filter element of web-app must be defined just like servlet.
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<filter>
<filter-name>f1</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>f1</filter-name>
<url-pattern>/servlet1</url-pattern>
</filter-mapping>
</web-app>