使用HandlerInterceptorAdapter实现访问过滤

最近在项目中用HandlerInterceptorAdapter实现了访问过滤。

关于HandlerInterceptorAdapter的学习,参考神玄晓的博客:http://www.cnblogs.com/lxaic/p/5851985.html   感谢他的分享!

1.配置文件,我这里是放在application.xml里面

1 <mvc:interceptors>
2     <mvc:interceptor>
3         <mvc:mapping path="/httpapi/**" />
4         <bean class="com.easylife.user.util.interceptor.HTTPAPICallInterceptor" />
5     </mvc:interceptor>
6 </mvc:interceptors>

 

 2.实现的Interceptor

 1 public class HTTPAPICallInterceptor extends HandlerInterceptorAdapter  {
 2     
 3     @Autowired
 4     private ApplicationConfig appConfig;
 5     
 6     @Override
 7     public boolean preHandle(HttpServletRequest request,
 8             HttpServletResponse response, Object handler) throws Exception {
 9         // 取得token
10         String access_token = request.getParameter("access_token");
11         if(StringUtils.isBlank(access_token)){
12             access_token = this.getHeader(request, "access_token");
13         }
14         if(StringUtils.isBlank(access_token)){
15             response.setCharacterEncoding("UTF-8");
16             response.getWriter().print("{\"success\": false,\"code\":\"invalid_token\",\"message\": \"Token was not recognised\"}");
17             return false;
18         }else{
19             String url=String.format(appConfig.getOauth2TokenCheckUrl(),access_token);
20             String return_json=send(url, "GET", null);
21             return_json=return_json.replace("{}", "");
22             JSONObject object=JSONObject.parseObject(return_json);
23             String keyFlg=object.getString("keyflg");
24             if(StringUtils.isNotBlank(keyFlg)){
25                 JSONArray arr=JSONObject.parseArray(keyFlg);
26                 if(arr.contains(appConfig.getOauth2TokenCheckKey())){
27                     // 合法token成功
28                     return true;
29                 }else{
30                     response.setCharacterEncoding("UTF-8");
31                     response.getWriter().print("{\"success\": false,\"code\":\"invalid_token\",\"message\": \"Resources no permissions to access\"}");
32                     return false;
33                 }
34             }else{
35                 response.setCharacterEncoding("UTF-8");
36                 response.getWriter().print("{\"success\": false,\"code\":\"invalid_token\",\"message\": " + return_json + "}");
37                 return false;
38             }
39         }
40     }

 

说明:

Interceptor 拦截以“/httpapi/”开头的请求,

使用preHandle方法,返回false表示拦截住了,不会再向controller层去请求。

返回true就可以继续走下去。

posted @ 2017-09-05 09:20  醉卧沙场~君莫笑  阅读(1126)  评论(0)    收藏  举报