Springmvc3 拦截器excludeUrlPattern

onlyring的文档库 2013-04-26

在用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.

相关推荐