设置web.xml中多个过滤器
程序员文章站
2022-04-03 08:57:58
...
我们在用struts2的时候,通常会使用默认的过滤器,定义拦截器,这样就可以控制请求过来的.action请求,但是如果我们直接使用.jsp来访问页面的话,就会有一些页面不能被拦截,会出现报错画面,影响网站的整体质量,这个时候我们就可以在web.xml中定义一个过滤器,让它来过滤.jsp的请求,做一些操作。代码如下:
<!-- 让Struts 2 的核心Filter拦截所有.action请求 --> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> <!-- 自定义一个过滤器 --> <filter> <filter-name>myFilter</filter-name> <filter-class>jy.filter.MyFilter</filter-class> </filter> <!-- 让自定义的Filter拦截所有.jsp请求 --> <filter-mapping> <filter-name>myFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping>
过滤器java代码如下:
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class MyFilter implements Filter {
public void destroy() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
System.out.println("自定义过滤器开始!");
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession();
String uri = request.getRequestURI();
uri = uri.split("/")[uri.split("/").length - 1];
if (uri.equals("login.jsp") || uri.equals("regist.jsp")) {
chain.doFilter(req, res);
} else {
if (session.getAttribute("user") != null) {
chain.doFilter(req, res);
} else {
response.sendRedirect(request.getContextPath() + "/login.jsp");
return;
}
}
}
public void init(FilterConfig arg0) throws ServletException {
}
}