Springmvc3 拦截器excludeUrlPattern
在用springmvc3时经常会碰到登录拦截这种需求,最新想到的办法是用拦截器,但在用拦截器时想让某些静态文件和某些url不需要拦截,实现如下:
spring-servlet.xml:
<mvc:resources mapping="/resources/**" location="/resources/" cache-period="31556926"/>
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.xxx.interceptor.UserLoginCheckInterceptor">
                <property name="excludeUrlPatterns">
                    <list>
                        <value>/login/*</value>
                        <value>/resources/**</value>
                    </list>
                </property>
            </bean>
        </mvc:interceptor>
    </mvc:interceptors>UserLoginCheckInterceptor.java
public class UserLoginCheckInterceptor extends HandlerInterceptorAdapter {
    private List<String> excludeUrlPatterns;
    private PathMatcher pathMatcher = new AntPathMatcher();
    public void setExcludeUrlPatterns(List<String> excludeUrlPatterns) {
        this.excludeUrlPatterns = excludeUrlPatterns;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String servletPath = request.getServletPath();
        for(String urlPattern : excludeUrlPatterns){
            if(pathMatcher.match(urlPattern,servletPath)){
                return true;
            }
        }
        HttpSession session = request.getSession();
        if(!Constants.CORRECT.equals(session.getAttribute(Constants.USER_NAME))){
            response.sendRedirect(request.getContextPath() +"/login.jsp");
            return false;
        }
        return true;
    }
}说明:
在配置文件中可以写不被拦截url pattern,写法和requestMapping一样,此处用到了AntPathMatcher类,springmvc中url映射本身也是用的此类,这里只是借用一下,即可完成urlpattern.
相关推荐
  zhangdy0    2020-05-31  
   HappyHeng    2020-05-28  
   HappyHeng    2020-05-16  
   whbing    2020-04-11  
   MicroBoy    2020-01-23  
   横云断岭    2020-01-04  
   Julywhj    2019-12-14  
   方志朋    2019-12-08  
   方志朋    2019-12-03  
   neweastsun    2019-11-11  
   whbing    2019-10-21  
   ScarletLina    2016-05-03  
   JINKAI    2019-03-27  
   zhongjcbill    2019-03-27  
   lihaoxiang    2018-07-23  
   mendeliangyang    2019-06-27