java 过滤器filter使用案例
主要需要 过滤器类 和配置文件
1.过滤器类 SessionFilter
package com.service; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class SessionFilter implements javax.servlet.Filter { public void destroy() { System.out.println("----Filter销毁----"); } public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { HttpServletRequest request=(HttpServletRequest) arg0; HttpServletResponse response=(HttpServletResponse) arg1; HttpSession session=request.getSession(); String path=request.getRequestURI(); Integer uid=(Integer)session.getAttribute("userid"); if(path.indexOf("/login.jsp")>-1){//登录页面不过滤 arg2.doFilter(arg0, arg1);//递交给下一个过滤器 return; } if(path.indexOf("/register.jsp")>-1){//注册页面不过滤 arg2.doFilter(request, response); return; } if(uid!=null){//已经登录 arg2.doFilter(request, response);//放行,递交给下一个过滤器 }else{ response.sendRedirect("/user/login"); } } public void init(FilterConfig arg0) throws ServletException { System.out.println("----Filter初始化----"); } }
2.配置web.xml
<filter> <filter-name>SessionFilter</filter-name> <!--过滤器--> <filter-class>com.service.SessionFilter</filter-class> </filter> <filter-mapping> <filter-name>SessionFilter</filter-name> <!--需要过滤的路径--> <url-pattern>/home/*</url-pattern> <!--<url-pattern>/user/*</url-pattern>--> </filter-mapping>