1.什么是fiter
Filter就像一个一个哨卡,用户的请求需要经过Filter,并且可以有多个过滤器
2.登陆filter作用
防止盗链接(没登陆就可以访问后台)
3.LoginFilter.java
package com.zy.filter; 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; public class LoginFilter implements Filter{ @Override public void destroy() { } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
//doFilter方法的第一个参数req,是ServletRequest 类型的,不支持setCharacterEncoding,
//所以要先强制转换为HttpServletRequest HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse)res; String uri = request.getServletPath();
//静态资源放行 if(uri.endsWith(".css")||uri.endsWith(".js")||uri.endsWith(".png")){ chain.doFilter(request, response); return; }
//登陆url放行 if(uri.endsWith("login.jsp")||uri.endsWith("login")){ chain.doFilter(request, response); return; } String loginname = (String)request.getSession().getAttribute("loginname");
//session没账号缓存,不放行 if(loginname == null){ response.sendRedirect("login"); return; }else{ chain.doFilter(request, response); return; } } @Override public void init(FilterConfig arg0) throws ServletException { } }
4.web.xml配置
<!-- 登陆过滤 --> <filter> <filter-name>LoginFilter</filter-name> <filter-class>com.zy.filter.LoginFilter</filter-class> </filter> <filter-mapping> <filter-name>LoginFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>