首页 > 代码库 > 【JavaEE企业应用实战学习记录】authorityFilter

【JavaEE企业应用实战学习记录】authorityFilter

 1 package sanglp.servlet; 2  3 import javax.servlet.*; 4 import javax.servlet.annotation.WebFilter; 5 import javax.servlet.annotation.WebInitParam; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpSession; 8 import java.io.IOException; 9 10 11 12 /**13  * Created by Administrator on 2016/10/5.14  */15 @WebFilter(filterName = "authority",urlPatterns = {"/*"},initParams = {16     @WebInitParam(name = "encoding",value = "http://www.mamicode.com/UTF-8"),17         @WebInitParam(name = "loginPage",value = "http://www.mamicode.com/chap2/login.jsp"),18         @WebInitParam(name = "proLogin", value="http://www.mamicode.com/chap2/proLogin.jsp")19 })20 public class AuthorityFilter implements Filter {21     //用于访问Filter的配置信息22     private FilterConfig config;23 24     @Override25     public void init(FilterConfig filterConfig) throws ServletException {26         this.config=filterConfig;27     }28 29     @Override30     public void destroy() {31         this.config=null;32     }33 34     @Override35     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {36         //获取该Filter的配置参数37         String encoding=config.getInitParameter("encoding");38         String loginPage=config.getInitParameter("loginPage");39         String proLogin=config.getInitParameter("proLogin");40         //设置request编码用的字符集41         servletRequest.setCharacterEncoding(encoding);42         HttpServletRequest hreq=(HttpServletRequest) servletRequest;43         HttpSession session=hreq.getSession(true);44         //获取客户请求的页面45         String requestPath=hreq.getServletPath();46         //如果session范围的user为null即表明没有邓丽。且用户请求的既不是登录页面,也不是处理登录的页面47         if(session.getAttribute("user")==null&&!requestPath.endsWith(loginPage)&&!requestPath.endsWith(proLogin)){48             servletRequest.setAttribute("tip","您还没有登录");49             servletRequest.getRequestDispatcher(loginPage).forward(servletRequest,servletResponse);50 51         }else{52             //履行请求53             filterChain.doFilter(servletRequest,servletResponse);54         }55     }56 }

 

【JavaEE企业应用实战学习记录】authorityFilter