How do you use the filterchain in Java?
In Java, FilterChain is an interface in Servlet that is used to filter or modify requests before passing them on to the next filter or servlet.
Here is an example using FilterChain:
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// 初始化操作
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
// 在请求被传递给下一个过滤器或servlet之前,可以对请求进行过滤或修改
String username = req.getParameter("username");
if (username != null && !username.isEmpty()) {
// 对请求进行修改
req.setAttribute("username", username.toUpperCase());
}
// 将过滤器链继续向下传递
chain.doFilter(req, res);
}
@Override
public void destroy() {
// 清理操作
}
}
In the example above, we implemented a custom filter called MyFilter and overrode its init, doFilter, and destroy methods.
In the doFilter method, we first convert ServletRequest and ServletResponse into HttpServletRequest and HttpServletResponse objects in order to utilize more HTTP-related methods and attributes.
Next, we can obtain the request parameters through the HttpServletRequest object, filter or modify the request. In this example, we will convert the value of username to uppercase and set it as an attribute of the request.
Finally, we invoke the doFilter method of FilterChain to pass the request and response to the next filter or servlet for processing.
Note: When configuring a filter in the web.xml file, it is important to bind the filter to a specific URL pattern or servlet name so that the filter can be invoked when a request is received.