How to configure Servlet Filters?

Answered

How to configure Servlet Filters?

Ninja Asked on 19th September 2018 in Servlet.
Add Comment
1 Answer(s)
Best answer

A filter is defined either via the @WebFilter annotation or in the deployment descriptor using the <filter> element. In this element, the following elements are used:

  • filter-name: used to map the filter to a servlet or URL
  • filter-class: used by the container to identify the filter type
  • init-params: initialization parameters for a filter

The container will instantiate exactly one instance of the Java class defining the filter per filter declaration in the deployment descriptor.

Here is an example of a filter declaration:


<filter>

 <filter-name>LoggingFilter</filter-name>

 <filter-class>com.demo.LoggingFilter</filter-class>

</filter>

Once a filter has been declared in the deployment descriptor, the <filter-mapping> element is used to define servlets and static resources in the Web application to which the filter is to be applied


<filter-mapping>

 <filter-name>LoggingFilter</filter-name>

 <url-pattern>/*</url-pattern>

</filter-mapping>

Here the Logging Filter is applied to all the servlets and static content pages in the Web application, because every request URI matches the ‘/*’ URL pattern.

Ninja Answered on 19th September 2018.
Add Comment