aop维护小程序登录状态,before方法获取request请求

    这是我的第一篇博客,可能码的不好。本人是一名菜鸟,写的不对的地方还望大神多多批评指点,欢迎留言,感激不尽。

   这次是记录使用aop维持小程序登录状态的一次随笔,可能基础不太好,卡在了如何在before方法中获得header中的3rdSession,也就是如何获得request。

   小程序每次请求需要验证用户是否登录,如果header中3rdSession与后台缓存中的不匹配,则判定该用户没有登录或登录超时。

   before方法里主要是拦截每次前端的请求,在before方法里进行3rdSession匹配,匹配成功返回loginStatus为1,否则loginStatus0,然后小程序通过后台传回的loginStatus判断用户是否登录。

   话不多说直接上代码。

   1.首先写一个切面类,里面是aop的before和after方法

 1 public class IsUserLoginAdviceImpl {
 2     public void isUserLogin() {
 3         //获得前端请求的request对象
 4         HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
 5         //初始化
 6         String third_Session ="";
 7         Cookie[] cookies = request.getCookies();
 8         for(Cookie cookie:cookies){
 9             if (cookie.getName().equals("third_Session")){
10                 //获得前端传来的登录凭证 third_Session
11                 third_Session=cookie.getValue();
12             }
13         }
14         //获得存入缓存中third_Session所对应的值,即用户的openId+sessionKey
15         String third_session_value = (String) CacheUtils.get(third_Session);
16         int loginStatus =0;
17         //不为空则说明登录验证成功,返回true
18         if (!StringUtils.isEmpty(third_session_value)){
19             loginStatus =1;
20             CacheUtils.put("loginStatus",loginStatus);
21         }else {
22             //loginStatus为0需要登录
23             CacheUtils.put("loginStatus",loginStatus);
24         }
25     }

  2.没有用注解的方式配aop,在xml文件中配置

  

 1 <!-- 指定切面所在的类-->
 2 <bean id="isUserLogin" class="cn.xxx.xxx.xxx.IsUserLoginAdviceImpl"/>
 3 <aop:config>
 4    <!-- 关联切面bean所对应的id-->
 5    <aop:aspect id="confirmLogin" ref="isUserLogin">
 6       <!--切点 execution(): 表达式主体,第一个*代表所有的返回值类型;后面是包名;第二个*号:表示类名,*号表示所有的类;
 7       第3个*表示所有的方法;最后一个..代表所有的参数 ,后面一个表达式是登录不需要拦截-->
 8       <aop:pointcut id="isUserLoginPointcut" expression="execution(* cn.xxx.xxx.xxx.*.*(..)) and !execution(* cn.xxx.xxx.xxx.UsersApiController.wxLogin(..))"/>
 9       <!-- 指定before方法,关联切点id-->
10       <aop:before method="isUserLogin" pointcut-ref="isUserLoginPointcut"/>
11       <!-- 指定after方法,关联切点id-->
12       <aop:after method="removeLoginStatusCache" pointcut-ref="isUserLoginPointcut"/>
13    </aop:aspect>
14 </aop:config>

 

这里开始一直纠结如何获得小程序header里携带的3rdSession,因为平时获得request都是在接口中(HttpServletRequest req)这样的方式,这种方式并不适用这种情况,最后查了一下获得request的几种方式,找到了答案。

1        //获得前端请求的request对象
2         HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

最后贴出原文地址,感兴趣的朋友可以看一下。https://blog.csdn.net/ChlatZed/article/details/72923351

您的每一次批评指正都会让我进步,欢迎留言指正!

 

posted @ 2018-03-31 00:31  会R闪的猫  阅读(842)  评论(0编辑  收藏  举报