SpringMVC URL拦截器

          app调用后台接口需要对其token及设备码进行检查,不匹对则拦截此次请求。公司要求做一个拦截器对app的请求进行检查,Spring框架自带一个HandlerInterceptor,我们只要实现这个接口就可以完成拦截器的制作。

  1.在Spirng配置文件中添加如下代码:

 

 
      
          
              
              
                  
                      
                         
                           /sign
                           /carInspect
                           /message
                           /question
                           /task
                      
                  
              
          
      
由于我只需要拦截几个接口的访问,所以我将需要拦截的接口参数写了进来。

2.实现接口

public class TokenVerificationInterceptor implements HandlerInterceptor{
	// 需要拦截的url
	public String[] interceptUrls;
	
	// 注入service
	@Autowired
	private ITokenService tokenService;
	// 获取url
	public void setInterceptUrls(String[] interceptUrls) {
		this.interceptUrls = interceptUrls;
	}
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
	}
	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object arg2) throws Exception {
		String requestUrl = req.getRequestURI().replace(req.getContextPath(), "");
		requestUrl = requestUrl.substring(requestUrl.indexOf("/"),requestUrl.lastIndexOf("/"));
        res.setContentType("text/html; charset=utf-8");
        //判断是否为App端请求
         if (null != interceptUrls && interceptUrls.length >= 1)  
            for (String url : interceptUrls) {  
                if (requestUrl.equals(url)) {
                	// 判断token和设备码能否匹配到
                	if (!checkToken(req)){
                		// 匹配失败拦截并向前台返回code 401
                		PrintWriter out = res.getWriter();
                		ResultBean result = new ResultBean();
                		result.setCode(ReturnCode.CODE_INTERCEPT);
                		result.setMessage("非法访问!");
                		JSONObject  jsonObject = JSONObject.fromObject(result);
                		out.print(jsonObject);
                		out.close();
                		return false;
                	}
                }  
            } 
		return true;
	}

ps:注意interceptUrls 属性名要与配置文件中property标签里面的name相同,同时要添加这个属性的set方法,获取拦截的URL参数,用req.getParameter()即可。如果想要回写数据,则用PrintWriter这个类即可

你可能感兴趣的:(java)