Servlet – Filter
A filter is an object that is used throughout the pre-and post-processing stages of a request. Filters are mostly used for filtering tasks such as server-side logging, authentication, and authorization, input validation, and so on.
The servlet is pluggable, which means that the entry is specified in the web.xml file. If the entry is deleted from the web.xml file, the filter is immediately deactivated. It must implement javax.servlet in order to generate a filter. Because servlets are constructed in the highly portable Java language and adhere to a common framework, they are very portable. As a result, it enables the creation of advanced server extensions in server and operating systems that are independent of one other.
Needs of Servlet Filters:
- Logging on the server.
- Request parameter is logged to log files.
- Authentication and authorization on the server.
- Compressing and Decompressing
- Encryption and decryption are two different things.
- Validation on the server.
Benefits of Servlet Filters:
- It can be plugged in.
- The filter is not reliant on a third-party resource.
- It requires little maintenance.
Servlet Filter Methods:
The filter interface consists of 3 life cycle methods.
|public void init(FilterConfig config) throws ServletException||This invokes the web container to indicate to a filter that is being placed into service. It takes one parameter, i.e. FilterConfig type or FilterConfig object.|
|public void doFilters(ServletRequest request,ServletResponse response,FileterChain chain) throws ServletException,IOException||The doFilter() function is called whenever a user requests a resource that is mapped to the filter. It’s used for filtering purposes.|
|public void destroy()||When the filter is removed from the service, this function is only called once.|
In this example, we’ll make a webpage index.html with a link that says “click here.” Click the link to invoke the servlet “ServletFilter.java” But before this Servlet is executed, the filter “MyFilter.java” associated with it will be executed which is specified in the deployment descriptor.
Click on “Click Here”
After Clicking the following link you will get this message