spring MVC拦截器01

spring MVC拦截
作用:身份校验,权限检查,防止非法訪问.
场景:一个bbs系统,用户没有登录就无法发帖或者删除评论;
一个博客系统,没有登录就无法发表博文,无法添加分类,无法删除博文.

spring MVC 拦截实现分为2步
(1)编写拦截器类,必须继承org.springframework.web.servlet.HandlerInterceptor
核心方法:

public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object arg2) throws Exception {

在该方法中进行权限校验,说白了,就是检查是否已成功登录,核心代码:

@Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object arg2) throws Exception {
        response.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession(true);

        String loginFlag = (String) session
                .getAttribute(Constant2.SESSION_KEY_LOGINED_FLAG);
        if (loginFlag == null
                ||( !loginFlag.equalsIgnoreCase(Constant2.FLAG_LOGIN_SUCCESS))) {
            String path=request.getRequestURI();//"/demo_channel_terminal/news/list"
            System.out.println("您无权訪问:"+path);
            String contextPath=request.getContextPath();

            request.setCharacterEncoding("UTF-8");
            response.setStatus(401);
            response.sendRedirect(contextPath);
            return false;
        }
        return true;
    }

(2)配置spring MVC配置文件
我的spring MVC配置文件名叫spring2-servlet.xml
拦截器相关配置:

<mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/bbs/json_add_bbs"></mvc:mapping>
            <mvc:mapping path="/news/json_add_tips"></mvc:mapping>
            <bean class="com.web.controller.intercept.MemberInterceptor">
            </bean>
        </mvc:interceptor>
    </mvc:interceptors>

拦截器配置
解释:当訪问/bbs/json_add_bbs和/news/json_add_tips 时就会应用拦截器类com.web.controller.intercept.MemberInterceptor(自己定义的)
訪问其它路径时不会应用该拦截器!!!

(3)项目结构
项目採用maven 构建
项目结构

注意:
preHandle方法中返回false,就会终止request过程,即不会运行action;

posted @ 2016-01-03 21:19  yxwkaifa  阅读(153)  评论(0编辑  收藏  举报