问题:后台生成验证码以后,存放到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相关的知识。了解不够的,可以脑补一些。