首页 > 代码库 > spring mvc 拦截器

spring mvc 拦截器

spring-mvc.xml配置文件里添加,配置不需要拦截的地址。

    <!--配置拦截器, 多个拦截器,顺序执行 -->
     <mvc:interceptors> 
           <mvc:interceptor>
                 <!--       /**的意思是所有文件夹及里面的子文件夹 
                       /*是所有文件夹,不含子文件夹 
                       /是web项目的根目录 -->
                     
                   <mvc:mapping path="/**" /> 
                   <!-- 需排除拦截的地址  --> 
                   <mvc:exclude-mapping path="/common/login"/> 
                   <mvc:exclude-mapping path="/festivalGoods/*"/> 
                   <mvc:exclude-mapping path="/orderInfo/addGift"/> 
                   <mvc:exclude-mapping path="/commonDict/*"/> 
                   <mvc:exclude-mapping path="/message/*"/> 
                   <bean id="commonInterceptor" class="com.iyihe.controller.common.CommonInterceptor"></bean> 
                <!--    这个类就是我们自定义的Interceptor -->
          </mvc:interceptor> 
       <!--    当设置多个拦截器时,先按顺序调用preHandle方法,然后逆序调用每个拦截器的postHandle和afterCompletion方法  -->
    </mvc:interceptors>

 CommonInterceptor.java 代码(主要实现登陆后生成token,之后每次请求都需要带上token进行验证用户是否有效)

package com.iyihe.controller.common;
import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.iyihe.dto.ResultDto;
import com.iyihe.service.IUserService;

public class CommonInterceptor  extends HandlerInterceptorAdapter{
        @Resource
        private IUserService userService;
    
        private final Logger log = LoggerFactory.getLogger(CommonInterceptor.class);

        public  static  final  String  LAST_PAGE = "lastPage";
        /** 
         * 在业务处理器处理请求之前被调用 
         * 如果返回false 
         *     从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链
         *     
         * 如果返回true 
         *    执行下一个拦截器,直到所有的拦截器都执行完毕 
         *    再执行被拦截的Controller 
         *    然后进入拦截器链, 
         *    从最后一个拦截器往回执行所有的postHandle() 
         *    接着再从最后一个拦截器往回执行所有的afterCompletion() 
         */  
        @Override
        public boolean preHandle(HttpServletRequest request,  
                HttpServletResponse response, Object handler) throws Exception { 
            response.setHeader("Access-Control-Allow-Origin","*");
            
            //获取token 判断是否有效
            String token=request.getParameter("token");
            boolean succ=userService.checkToken(token);
            //有效 请求需要请求的页面
            if(succ){
                return true;
            }//无效 请用户重新登陆
            else{
                ResultDto dto=new ResultDto();
                dto.setSuccess(false);
                dto.setResultInfo("token无效");
                this.responseOutWithJson(response,dto);
                return false;
            }
        } 
        protected void responseOutWithJson(HttpServletResponse response,  
                ResultDto responseObject) {  
            response.setCharacterEncoding("UTF-8");  
            response.setContentType("application/json; charset=utf-8");  
            PrintWriter out = null;  
            try {  
                out = response.getWriter();  
                out.append(responseObject.toJSON());
            } catch (IOException e) {  
                e.printStackTrace();  
            } finally {  
                if (out != null) {  
                    out.close();  
                }  
            }  
        }  

        /**
         * 在业务处理器处理请求执行完成后,生成视图之前执行的动作   
         * 可在modelAndView中加入数据,比如当前时间
         */
        @Override  
        public void postHandle(HttpServletRequest request,  
                HttpServletResponse response, Object handler,  
                ModelAndView modelAndView) throws Exception {   
            log.info("==============执行顺序: 2、postHandle================");  
            if(modelAndView != null){  //加入当前时间  
                modelAndView.addObject("haha", "测试postHandle");  
            }  
        }        
        /** 
         * 在DispatcherServlet完全处理完请求后被调用,可用于清理资源等    
         * 当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion() 
         */  
        @Override  
        public void afterCompletion(HttpServletRequest request,  
                HttpServletResponse response, Object handler, Exception ex)  
                throws Exception {  
            log.info("==============执行顺序: 3、afterCompletion================");  
        }  
}

 Login.java

package com.iyihe.controller.common;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iyihe.dto.ResultDto;
import com.iyihe.dto.UserDto;
import com.iyihe.entity.User;
import com.iyihe.service.IUserService;


/**
 * 登陆
 * @author wxm
 * 2016年12月7日
 */
@Controller
@RequestMapping("/common")
public class LoginController {
    @Resource
    private IUserService userService;
    @RequestMapping("/login")
    @ResponseBody
    public ResultDto login(User user,HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin","*");
        ResultDto dto=new ResultDto();
        try {
            //判断用户名和密码是否存在该用户
            UserDto userDto=new UserDto();
            userDto=userService.login(user);//如果用户名密码争取额生成新的token
            //如果存在
            if(userDto.isSucc()){
                //修改user表
                dto.setData(userDto);
                dto.setSuccess(true);
                dto.setResultInfo("登陆成功");
            }else{
                //
                dto.setSuccess(false);
                dto.setResultInfo("用户名或密码错误");
            }
            return dto;
        } catch (Exception e) {
            dto.setResultInfo("登陆失败");
            dto.setSuccess(false);
            e.printStackTrace();
            return dto;
        }
        
    }
}

 

spring mvc 拦截器