Servlet Filter vs Spring Interceptor
Servlet Filter and Spring Interceptors are important concepts in java world. But there is always confusion between both concepts. Both serve almost the same concept but there are differences when to use and for which purpose.
Servlet Filter
|
Spring Interceptor
|
A Servlet Filter is used in the web layer only, you can’t use it outside of a web context.
|
Interceptors can be used anywhere.
|
For authentication of web pages, you would use a servlet filter.
|
Security stuff in your business layer or logging/bug tracking (a.k.a.
independent of the web layer) you would use an Interceptor.
|
For the Login authentication and auditing of incoming requests from web pages, we should use a servlet filter.
|
While for implementing your business layer logging and auditing and many other along feature we should use an Interceptor.
|
Filters implement javax.servlet.Filter
|
Interceptors implement org.springframework.web.servlet.HandlerInterceptor
|
Further Reading
http://array151.com/blog/servlets/
http://array151.com/blog/servlet-filter/
http://array151.com/blog/spring-interceptors/
http://array151.com/blog/advantages-of-spring-interceptor-over-servlet-filter/
Difference between Servlet Filter and Servlet Listener
Servlet Filter
|
Servlet Listener
|
Servlet Filter is used for monitoring request and response from client to the servlet, or to modify the request and response, or to audit and log.
|
Servlet Listener is used for listening to events in a web containers, such as when you create a session, or place an attribute in an session or if you passivate and activate in another container, to subscribe to these events you can configure listener in web.xml, for example HttpSessionListener.
|
Filter is an object which transform the request and response (header as well as content).
|
You can monitor and react to events in a servlet’s life cycle by defining listener objects whose methods get invoked when life cycle events occur.
|
Filters are used for pre and post process requests. Look at the javax.servlet.Filter in your tomcat/jboss/other container javadoc.
|
Where as the listeners are like triggers that can be attached to events in your app server (let’s use the term container here). With listeners you can track application-level, session-level, life-cycle changes, attribute changes etc. The implemented interfaces are javax.servlet.Listener interface.
|
Filters work with servlet container dispatches. For one listener invocation there may be multiple filters/servlet invocations. Filters implement javax.servlet.Filter
|
While listeners get triggered for an actual physical request listeners implements javax.servlet.ServletContextListener and other listed listeners.
|
Servlet Listener
Servlet Listener is used for listening to events in a web container, such as when you create a session or place an attribute in a session or if you passivate and activate in another container, to subscribe to these events you can configure listener in web.xml, for example, HttpSessionListener.
Listeners get triggered for an actual physical request that can be attached to events in your app server .With listeners, you can track application-level, session-level, life-cycle changes, attribute changes etc.
You can monitor and react to events in a servlet’s life cycle by defining listener objects whose methods get invoked when lifecycle events occur.
Event
Event is the occurrence of something, an event can be the initialization of the application, destroying an application, request from the client, creating/destroying a session, attribute modification in session etc.
Servlet API
This provides different types of Listener interfaces that we can implement and configure in web.xml.
Servlet API provides following event objects.
Event Object
|
Description
|
javax.servlet.AsyncEvent
|
Event that gets fired when the asynchronous operation initiated on a ServletRequest has completed, timed out, or produced an error.
|
javax.servlet.http.HttpSessionBindingEvent
|
Events of this type are either sent to an object that implements HttpSessionBindingListener when it is bound or unbound from a session, or to a HttpSessionAttributeListener that has been configured in the web.xml when any attribute is bound, unbound or replaced in a session.
The session binds the object by a call to HttpSession.setAttribute and unbinds the object by a call to HttpSession.removeAttribute. We can use this event for cleanup activities when object is removed from session. |
javax.servlet.http.HttpSessionEvent
|
Event notifications for changes to sessions within a web application.
|
javax.servlet.ServletContextAttributeEvent
|
Event notifications about changes to the attributes of the ServletContext of a web application
|
javax.servlet.ServletContextEvent
|
Event notifications about changes to the servlet context of a web application
|
javax.servlet.ServletRequestEvent
|
Event notification about lifecycle of ServletRequest.
|
javax.servlet.ServletRequestAttributeEvent
|
Event class for notifications of changes to the attributes of the servlet request in an application
|
Servlet API provides following Listener interfaces :-
Listener Object
|
Description
|
javax.servlet.AsyncListener
|
Listener that will be notified in the event that an asynchronous operation initiated on a ServletRequest to which the listener had been added has completed, timed out, or resulted in an error
|
javax.servlet.ServletContextListener
|
Interface for receiving notification events about ServletContext lifecycle changes
|
javax.servlet.ServletContextAttributeListener
|
Interface for receiving notification events about ServletContext attribute changes
|
javax.servlet.ServletRequestListener
|
Interface for receiving notification events about requests coming into and going out of scope of a web application
|
javax.servlet.ServletRequestAttributeListener
|
Interface for receiving notification events about ServletRequest attribute changes
|
javax.servlet.http.HttpSessionListener
|
Interface for receiving notification events about HttpSession lifecycle changes
|
javax.servlet.http.HttpSessionBindingListener
|
Causes an object to be notified when it is bound to or unbound from a session.
|
javax.servlet.http.HttpSessionAttributeListener
|
Interface for receiving notification events about HttpSession attribute changes
|
javax.servlet.http.HttpSessionActivationListener
|
Objects that are bound to a session may listen to container events notifying them that sessions will be passivated and that session will be activated. A container that migrates session between VMs or persists sessions is required to notify all attributes bound to sessions implementing HttpSessionActivationListener.
|
Example : Counting logged in users Using HttpSessionEvent and HttpSessionListener
<form action="login">
Name:<input type="text" name="userName"><br>
Password:<input type="password" name="password"><br>
<input type="submit" value="Login"/>
</form>
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class First extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String username =request.getParameter("userName");
out.print("Welcome "+ userName);
HttpSession session=request.getSession();
session.setAttribute("userName",userName);
ServletContext ctx=getServletContext();
int loggedInUsers=(Integer)ctx.getAttribute("loggedInUsers");
out.print("<br>Total logged in users= "+loggedInUsers);
out.close();
}
}
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
@WebListener
publicclassMyListenerimplementsHttpSessionListener{
ServletContext ctx=null;
static int loggedInUsers=0;
publicvoid sessionCreated(HttpSessionEvent sessionEvent){
loggedInUsers++;
ctx=e.getSession().getServletContext();
ctx.setAttribute("loggedInUsers", loggedInUsers);
}
publicvoid sessionDestroyed(HttpSessionEvent sessionEvent){
loggedInUsers--;
ctx.setAttribute("loggedInUsers",loggedInUsers);
}
}
Reference :-
http://www.journaldev.com/1945/servletcontextlistener-servlet-listener-example
http://www.javatpoint.com/Event-and-Listener-in-Servlet
Servlet Filter
A filter is an object that dynamically intercepts requests and responses to transform or use the information contained in the requests or responses.
Filters typically do not themselves create responses but instead provide universal functions that can be “attached” to any type of servlet or JSP page.
The filter is run before rendering view but after controller rendered response.
A Filter is used in the web layer only as it is defined in web.xml.
Filters are more suitable when treating your request/response as a black box system. They’ll work regardless of how the servlet is implemented.
Filters are used to perform filtering tasks such as login authentication ,auditing of incoming requests from web pages, conversion, logging, compression, encryption and decryption, input validation etc.
A Servlet Filter is used in the web layer only, you can’t use it outside of a
web context.
Filter Interface methods :-
Method | Description |
---|---|
public void init(FilterConfig config) | init() method is invoked only once. It is used to initialize the filter. |
public void doFilter( HttpServletRequest request, HttpServletResponse response, FilterChain chain) |
doFilter() method is invoked every time when user request to any resource, to which the filter is mapped. |
public void destroy() | This is invoked only once when filter is taken out of the service. |
Filter Example :-
MyFilter.java
import javax.servlet.*; import java.io.IOException; public class MyFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { // your code goes here } public void destroy() { } }
HelloServlet.java
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.*; public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.print("<br>Hello from servlet<br>"); } }
Configuring the Servlet Filter in web.xml
<web-app> <servlet> <servlet-name>Servlet1</servlet-name> <servlet-class>HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Servlet1</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <filter> <filter-name>Filter1</filter-name> <filter-class>MyFilter</filter-class> </filter> <filter-mapping> <filter-name>Filter1</filter-name> <url-pattern>/servlet1</url-pattern> </filter-mapping> </web-app>
For more detail :-
https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/Filter.html
Servlets
Servlets are programs that run on a Web or Application server and act as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server.
A servlet is simply a class which responds to a particular type of network request – most commonly an HTTP request.
Basically, servlets are usually used to implement web applications – but there are also various frameworks which operate on top of servlets (e.g. Struts) to give a higher-level abstraction than the “here’s an HTTP request, write to this HTTP response” level which servlets provide.
Servlets run in a servlet container which handles the networking side (e.g. parsing an HTTP request, connection handling etc). One of the best-known open source servlet containers is Tomcat.
The container will take care of things like wrapping the whole thing in a HTTP response object and send it over to the client (say a browser).
The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines life-cycle methods. When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services.
Lifecycle
Servlets are now java classes whose lifecycle will be maintained by the container but their reaction to incoming HTTP requests will be decided by you.
You do that by writing what-you-want-to-do in the pre-defined methods like init(), doGet(), doPost() etc.
When a Servlet is requested for the first time or when the web app starts up, the servlet container will create an instance of it and keep it in memory during the web app’s lifetime.
The same instance will be reused for every incoming request whose URL matches the servlet’s URL pattern. You can access the requested data by HttpServletRequest and handle the response by HttpServletResponse. Both objects are available as method arguments inside of any of the overridden methods of HttpServlet, such as doGet() to preprocess a request and doPost() to post-process a request. See also How do servlets work? Instantiation, sessions, shared variables and multithreading.