java2db

Servlet Filter ( Request and Response filters in servlets ) example



Servlet filter is a java class, that implements javax.servlet.Filter interface.It is used to trap the client request and server response to do additional pre-request , response processing logics.

 

Servlet Filter These are useful to add additional modifications without disturbing the existing programs.
Servlet Filter Servlet filter that integrates in web.xml with the URL pattern of the required servlet/servlets.
Servlet Filter Servlet  filter can intercepts and  access the  javax.servlet.ServletRequestjavax.servlet.ServletResponse objects that provide access to the HTTP request and response, and also a javax.servlet.FilterChain object.

 
Servlet Filter

 

create a servletThe filter can modify the headers only if the response has not already been committed.

 

Servlet Filter Filter lifecycle methods :

Servlet Filter init() : Called by the web container to indicate to a filter that it is being placed into service.We can write initialization logics in this method.

Servlet Filter doFilter() :The doFilter method of the Filter is called by the container each time of request from a client or response to the client .
Servlet Filter destroy() :Called by the web container to indicate to a filter that it is being taken out of service.

 

Servlet Filter Example for Servlet Filter :

Servlet Filter Directory Structure in eclipse :
Servlet Filter

Servlet Filter login.jsp

Servlet Filter LoginFilter.java

Servlet Filter LoginServlet.java

Servlet Filter web.xml

Servlet Filter Login_success.jsp

Servlet Filter Login_fail.jsp

Execution result :

Enter the URL (http://localhost:8080/LoginWithFiltersApp/login.jsp) in the browser address bar and enter the login id , password.

Servlet Filter

 

Click the submit button . So that the request goes through the servlet filter and  gives the below response through the same filter.
Servlet Filter

While execution , we will get the below output in the console.
Servlet Filter




Related Posts :
Kill or invalidate session using session id ( concurrent login )
URL rewriting in servlets ( Servlet session tracking )
Servlet Cookies ( Servlets session tracking with cookie )
Hidden form field in servlets ( Servlet session tracking )
Request attributes in servlet with an example ( Attribute scope )
Session attributes in servlet with example (Attribute scope)
ServletConext Attributes in servlet ( Attribute scope )
The sendRedirect (servlets are in different web applications)
   [will not be published]



^ <