The following example code demonstrates how to write a Program in JSP to Display Multiple Filters.
Here is an example code for a JSP program that displays multiple filters.
- Filter1.java
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
@WebFilter("/filter1")
public class Filter1 implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("Filter 1 is called");
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {}
public void destroy() {}
}
- Filter2.java
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
@WebFilter("/filter2")
public class Filter2 implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("Filter 2 is called");
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {}
public void destroy() {}
}
- web.xml
<web-app>
<filter>
<filter-name>Filter1</filter-name>
<filter-class>Filter1</filter-class>
</filter>
<filter-mapping>
<filter-name>Filter1</filter-name>
<url-pattern>/filter1</url-pattern>
</filter-mapping>
<filter>
<filter-name>Filter2</filter-name>
<filter-class>Filter2</filter-class>
</filter>
<filter-mapping>
<filter-name>Filter2</filter-name>
<url-pattern>/filter2</url-pattern>
</filter-mapping>
</web-app>
This code defines two filters, Filter1
and Filter2
, each of which implements the Filter
interface. When a request is made to /filter1
, Filter1
is called and prints “Filter 1 is called” to the console. Similarly, when a request is made to /filter2
, Filter2
is called and prints “Filter 2 is called” to the console. The web.xml
file maps each filter to the corresponding URL pattern.