
In java, there is a concept of a filter class which is used in pre processing and post processing.
Filters are generally used for
1)Validation of user inputs
2)Encryption Decryption
3)User Logging
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. So it requires less maintainance.
How to create a Filter?
To create a Filter,
- It should implement the Filter interface.
Similar to a Servlet, a filter Interface has some life cycle methods.
->public void init(FilterConfig config) – Similar to a servlet, it is used for initialization of that filter.
->public void init(FilterConfig config) – It is used to perform the filteration tasks and it accepts the http request object.
->public void destroy() – Used to destroy filter object once all activities are done.
2. FilterChain Interface – The object of FilterChain is responsible to invoke the next filter or resource in the chain.It only has doFilter method and it passes the control to the next filter.
Let’s look at the implementation of the filter below.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
public class FilterExample implements Filter{
public void init(FilterConfig arg0) throws ServletException {
//steps to initialize
}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
PrintWriter out=resp.getWriter();
out.print("Filter method is called as part of pre-processing");
chain.doFilter(req, resp);//sends request to next resource
out.print("filter is invoked as part of post processing");
}
public void destroy() {
}
}
Now let’s define the mapping for the same in web.xml so that filter is configured to be used before the servlet is called.
<web-app>
<servlet>
<servlet-name>servletsample</servlet-name>
<servlet-class>ServletExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servletsample</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<filter>
<filter-name>filtersample</filter-name>
<filter-class>FilterExample</filter-class>
</filter>
<filter-mapping>
<filter-name>filtersample</filter-name>
<url-pattern>/servlet1</url-pattern>
</filter-mapping>
</web-app>
Let’s define the servlet which would finally be called. The filter class would fwd the request to this servlet through the filter chain as it is next resource.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class ServletExample extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<br>Servlet is called<br>");
}
}