Servlet filter:
Servlet filters are the objects that are used to perform some filtering tasks. A filter can be applied to a servlet, JSP, or HTML.
Servlet filters are mainly used for the following tasks:
- Pre-processing: A servlet filter is used for pre-processing of requests before it accesses any resource on the server side.
- Post-processing: A servlet filter is used for post-processing the response before it is sent back to the client.
How to create a filter?
Implement javax.servlet.Filter interface to create a filter.
Filter interface:
To create a filter you have to implement a filter interface. The filter interface is in javax.servlet package javax.servlet.Filter. It provides the life cycle methods of a filter.
Methods of filter interface:
1. init(FilterConfig config): This method is used to initialize the filter. It is called only once by the web container.
Syntax:
public void init(FilterConfig config)
2. doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain): This method is used for performing pre-processing and post-processing tasks. It is called every time a request/response comes for a resource to which the filter is mapped.
Syntax:
public void doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain)
3. destroy(): This method is called only once by the web container when the filter is taken out of the service.
Syntax:
public void destroy()
FilterChain interface:
FilterChain object is used to call the next filter or a resource if it is the last filter in filter chaining.
Method of FilterChain interface:
1. doFilter(HttpServletRequest request, HttpServletResponse response): This method is used to call the next filter in filter chaining.
Syntax:
public void doFilter(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
How to define a filter in web.xml?
<filter> attribute is used to define a filter in web.xml.
Syntax:
//Other attributes. <filter> <filter-name>filterName </filter-name> <filter-class>filterClass</filter-class> </filter> <filter-mapping> <filter-name>filterName</filter-name> <url-pattern>urlPattern</url-pattern> </filter-mapping> //Other attributes. </web-app>
Example:
LoginFilter.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* This class is used as a filter.
* @author W3schools360
*/
public class LoginFilter implements Filter {
private static final long serialVersionUID = 1L;
public void init(FilterConfig filterConfig)
throws ServletException {
}
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//get parameters from request object.
String userName = request.getParameter("userName").trim();
String password = request.getParameter("password").trim();
//check for null and empty values.
if(userName == null || userName.equals("") ||
password == null || password.equals("")){
out.print("Please enter both username " +
"and password. ");
RequestDispatcher requestDispatcher =
request.getRequestDispatcher("/login.html");
requestDispatcher.include(request, response);
}//Check for valid username and password.
else if(userName.equals("jai") && password.equals("1234")){
chain.doFilter(request, response);
}else{
out.print("Wrong username or password. ");
RequestDispatcher requestDispatcher =
request.getRequestDispatcher("/login.html");
requestDispatcher.include(request, response);
}
}
public void destroy() {
}
}
WelcomeServlet.java
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;
/**
* This class is used to print login message
* if user logged in successfully.
*/
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//no-argument constructor
public WelcomeServlet() {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<h1>You are logged in successfully.</h1>");
out.close();
}
}
login.html
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
<form action="WelcomeServlet" method="POST">
Username:<input type="text" name="userName">
<br><br>
Password:<input type="password" name="password">
<br><br>
<input type="submit" value="login">
</form>
web.xml
<!--?xml version="1.0" encoding="UTF-8"?-->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemalocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>
com.w3schools.business.WelcomeServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/WelcomeServlet</url-pattern>
</servlet-mapping>
<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>
com.w3schools.business.LoginFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/WelcomeServlet</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>