问题描述:
安卓课程设计,用户登陆时做了个验证码的功能,在WEB端可以正常运行。
在安卓跑时发现服务器端可以正确获取前端传来的验证码的值,但是从session里取验证码的值时却一直是null。
经过DEBUG发现两者的SESSIONID值不同了,根本不是一个SESSION对象,也不太清楚是什么原因造成的,如下图所示:
解决办法:
曲线救国,服务器端生成并存储验证码后,也存储SESSIONID的值至cookie中并发送给前台。前台表单传递信息时在将该SESSIONID传递过来,后台通过SESSIONID查找指定的SESSION对象,再去获取其里面存储的验证码值进行校验比对。
关键代码如下:
java添加、获取、清除cookie
private final static String URL_CODE = "UTF-8";
public static void addCookie(HttpServletResponse resp, String key, String value) { try { Cookie cookie = new Cookie(key, URLEncoder.encode(value, URL_CODE)); cookie.setPath("/"); resp.addCookie(cookie); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } public static String getCookie(HttpServletRequest req, String key) { Cookie[] cookies = req.getCookies(); if (cookies != null) { try { for (Cookie cookie : cookies) { if (cookie.getName().equals(key)) { return URLDecoder.decode(cookie.getValue(), URL_CODE); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return "-1"; } public static void removeLogin(HttpServletRequest req, HttpServletResponse resp) { Cookie[] cookies = req.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { cookie.setMaxAge(0); cookie.setPath("/"); resp.addCookie(cookie); } } }
服务器端根据SESSIONID获取指定的SESSION对象:参考自https://blog.csdn.net/feicongcong/article/details/76034269
新建一个类MySessionContext.java
/* * 采用单例模式设计 */ public class MySessionContext { private static MySessionContext instance; private HashMap mymap; private MySessionContext() { mymap = new HashMap(); } public static MySessionContext getInstance() { if (instance == null) { instance = new MySessionContext(); } return instance; } public synchronized void AddSession(HttpSession session) { if (session != null) { mymap.put(session.getId(), session); } } public synchronized void DelSession(HttpSession session) { if (session != null) { mymap.remove(session.getId()); } } public synchronized HttpSession getSession(String session_id) { if (session_id == null) return null; return (HttpSession) mymap.get(session_id); } }
在新建一个监听类SessionListener.java
public class SessionListener implements HttpSessionListener { public static Map userMap = new HashMap(); private MySessionContext myc = MySessionContext.getInstance(); public void sessionCreated(HttpSessionEvent httpSessionEvent) { myc.AddSession(httpSessionEvent.getSession()); } public void sessionDestroyed(HttpSessionEvent httpSessionEvent) { HttpSession session = httpSessionEvent.getSession(); myc.DelSession(session); } }
web.xml配置:
<listener> <listener-class>SessionListenerlistener-class> listener>
使用方式
//校验验证码 以sessionID的方式获取指定session对象,在去获取验证码 MySessionContext myContext= MySessionContext.getInstance(); HttpSession session = myContext.getSession(sessionID);
//在根据指定的session对象去获取存储其中的校验码的值 String checkCode = (String) session.getAttribute("CHECKCODE_SERVER");