解决android每次请求,后台sessionId都会变换(springboot配置web.xml)

24 篇文章 0 订阅

问题:后台生成验证码以后,存放到session缓存中,将验证码发送给指定手机,当安卓手机输入验证码调用注册接口时候,后台接口从session中无法取出放入的验证码。

原因:android每次请求,后台sessionId都会变换。

解决方法:

1. 配置web.xml

springboot项目默认是没有配置web.xml文件的,所以需要自己配置(idea开发工具):

2.通过图中步骤配置完成web.xml文件以后开始写代码:

如上图所示分别创建两个类:

类MySessionContext:
package com.blog.xiangqin.utils;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

public class MySessionContext {
    private static HashMap mymap = new HashMap();
    public static synchronized void AddSession(HttpSession session) {
        if (session != null) {
            mymap.put(session.getId(), session);
        }
    }
    public static synchronized void DelSession(HttpSession session) {
        if (session != null) {
            mymap.remove(session.getId());
        }
    }
    public static synchronized HttpSession getSession(String session_id) {
        if (session_id == null)
            return null;
        return (HttpSession) mymap.get(session_id);
    }
}

类MySessionListener:

package com.blog.xiangqin.utils;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class MySessionListener implements HttpSessionListener {
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        MySessionContext.AddSession(httpSessionEvent.getSession());
    }
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        HttpSession session = httpSessionEvent.getSession();
        MySessionContext.DelSession(session);
    }

}

3.最后再在创建的web.xml中做监听配置(监听包名、类名指向地址根据项目而定):

web.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
        <listener>
            <listener-class>com.blog.xiangqin.utils.MySessionListener</listener-class>
        </listener>
</web-app>

4. 开始使用创建好的工具存放session,并且根据sessionId来取值session中存放的验证码:

获取验证码接口存放session(randomNum是随机生成验证码):
session.setAttribute("code",randomNum);
MySessionContext.AddSession(session);

5.启动安卓调用获取验证码接口,在调用注册接口:

   在注册接口,根据安卓传过来的sessionId取出我们存放的验证码:

session = MySessionContext.getSession(user.getSessionId());
System.out.println("...请求注册接口:session.getId()="+session.getId());
String code = (String) session.getAttribute("code");

这里面用到了springboot创建web.xml,sessionId相关的知识。了解不够的,可以脑补一些。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值