首先在web.xml中配置,配置方法与字符拦截器大同小异,配置如下:
<!-- 使用filter实现登录控制 --> <filter> <filter-name>SessionFilt</filter-name> <filter-class>com.ed.web.admin.action.LoginFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>SessionFilt</filter-name> <url-pattern>要拦截的页面</url-pattern> </filter-mapping>
和普通过滤器配置没什么区别,就是多了两个初始化参数,两个参数的作用分别是:
encoding----->用来指定一个具体的字符集
forceEncoding------->Spring的早期版本这个参数作用很单一,当request中已经被指定了一个字符集的时候是否再将用 endcoding对应的字符集设置到request中去。举个例子来说明,假如说过滤器就像上面 那样被配置到web.xml了,当请求 被提交之后,过滤器会判断request.getCharacterEncoding()是否为null,如果是null那么就会进行 request.setCharacterEncoding("UTF-8")的操作,如果不是null那么过滤器什么也不会做。
看下拦截后的具体逻辑:
public class LoginFilter implements Filter { private String excludedPaths; private String [] excludedPathArray; @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { // TODO Auto-generated method stub HttpServletRequest request = (HttpServletRequest)arg0; HttpServletResponse response = (HttpServletResponse)arg1; HttpSession session = request.getSession(); //需要放行的路径 if( request.getRequestURI().indexOf("/admin/login")!= -1 ||request.getRequestURI().indexOf("/pac/ky")!= -1 ||request.getRequestURI().indexOf("/pac/yh")!= -1 ||request.getRequestURI().indexOf("/pac/yn")!= -1 ||request.getRequestURI().indexOf("/pac/yn")!= -1){ arg2.doFilter(arg0, arg1); } else{ if(session.getAttribute("loginUser")==null ){ response.sendRedirect(request.getContextPath()+"/timeout.jsp"); }else { arg2.doFilter(arg0, arg1); } } } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }