ajax实现用户登陆,退出,java做后端
最近http老师布置了个任务,用cookie完成登陆,退出。Http老师讲的是node.js写后端,由于自己还是擅长java些,还是用Java做了。
以前跟着教程写过一个网站,当初是用jsp+servlet+javabean去实现的,现在想结合json和ajax实现一下,搞了一下午,遇到了些问题,总结一下
1.当初在servlet中用cookie存储中文并没有出现乱码问题,可能进行了封装吧。我在Java中用cookie去存储用户名出现了中文乱码问题,报错了。。查阅资料使用URLEncoder.encode进行编码
2.编码之后使用js取cookie出现中文乱码问题,javascript中有个函数进行解码操作:decodeURIComponent()
3.学习并掌握js取cookie,删除cookie的方法
代码如下:
package bussiness; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.sql.SQLException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.json.JSONObject; public class userOperation { // 定义全局变量 protected HttpServletResponse response; protected HttpServletRequest request; private final static String URL_CODE = "UTF-8"; //解决cookie存中文乱码 /* * 统一获取数据的入口 */ public String getData(HttpServletRequest req, HttpServletResponse resp) throws SQLException { request = req; response = resp; if ("userLoginCheck".equals(flags)) return userLoginCheck(); else if("userLoginOut".equals(flags)) return userLoginOut(); return ""; } /* * 自定义用户注销 */ private String userLoginOut() { JSONObject jsonObject = new JSONObject(); addCookie(response,"userName",""); jsonObject.put("message", "userLoginOutSuccess"); return jsonObject.toString(); } /* * 自定义用户登录函数 */ private String userLoginCheck() { JSONObject jsonObject = new JSONObject(); try { QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource()); String sql = "select * from http_login where name=\'" + name + "\' and password=\'" + password + "\'"; userOperation user = qr.query(sql, new BeanHandler<userOperation>(userOperation.class)); if(user!=null){ jsonObject.put("statusCode", 200); jsonObject.put("referer", "index.html"); jsonObject.put("message", "用户登录成功。"); //存储登录信息 addCookie(response,"userName",user.getName()); }else{ jsonObject.put("statusCode", 404); jsonObject.put("referer", "/"); jsonObject.put("message", "用户或密码错误."); } } catch (SQLException e) { e.printStackTrace(); } return jsonObject.toString(); } /* * addCookie,setCookie函数 */ private 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(); } } private 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 null; } // 实体bean参数以及getter/setter private String name; private String password; private String flags; public String getFlags() { return flags; } public void setFlags(String flags) { this.flags = flags; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="../js/jquery-1.11.3.min.js"></script> <script type="text/javascript"> $(function() { var str = ""; var name = decodeURIComponent(getCookie("userName")); //js取cookie出现中文乱码问题,使用decodeURIComponent()进行解码 console.log(name); if (name == "null") { $("#Info").html("您好,请先登陆!!"); } else { $("#Info").html("您好,欢迎回来:" + name); } //登陆事件 $("#userLogin").click(function() { var name = decodeURIComponent(getCookie("userName")); //js取cookie出现中文乱码问题,使用decodeURIComponent()进行解码 if (name != "null") { $("#tips").html("您已经登录,无需重复登陆!" + \'<br/>\'); } else { window.location.href = "userLogin.html"; } }); //注销事件 $("#userLoginOut").click(function() { var name = decodeURIComponent(getCookie("userName")); //js取cookie出现中文乱码问题,使用decodeURIComponent()进行解码 if (name != "null") { delCookie(\'userName\'); location.reload() ; } else { $("#tips").html("您还未登录,请先登陆!" + \'<br/>\'); } }) //自定义正则读取cookie function getCookie(name) { var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)")); if (arr != null) return arr[2]; return null; } //字符串分割方式读取cookie function getCookie2(name) { var strcookie = document.cookie; //获取cookie字符串 var arrcookie = strcookie.split("; "); //分割 console.log(arrcookie); //遍历匹配 for (var i = 0; i < arrcookie.length; i++) { var arr = arrcookie[i].split("="); if (arr[0] == name) { return arr[1]; } } return ""; } //js删除cookie function delCookie(name) { var exp = new Date(); exp.setTime(exp.getTime() - 1); var cval = decodeURIComponent(getCookie(name)); if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString() + ";path=/"; } }) </script> </head> <body> <div id="Info"></div> <br /> <span id="tips" style="color:red"></span> <button id="userLogin">登陆</button> <button id="userLoginOut">退出登陆</button> </body> </html>
<%@ page contentType="text/html; charset=utf-8" import="bussiness.userOperation,java.util.Enumeration,java.io.*,java.net.URLEncoder,java.util.HashMap"%> <jsp:useBean id="myHandle" class="bussiness.userOperation"></jsp:useBean> <jsp:setProperty property="*" name="myHandle"/> <% //测试使用,打印参数 Enumeration e = request.getParameterNames(); while (e.hasMoreElements()) { System.out.println(e.nextElement()); } System.out.println("flags:" + myHandle.getFlags()); //获取处理结果 String returnStr = myHandle.getData(request, response); System.out.println("[DEBUG][returnStr]" + returnStr); //向前台输出结果 out.println(returnStr); %>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>FormJson</title> <script type="text/javascript" src="../js/jquery-1.11.3.min.js"></script> <script type="text/javascript"> $(function() { $("#submit").click(function() { data1 = $("#myForm").serializeArray(); //console.log(data1); var str = ""; jQuery.ajax({ type : \'POST\', //请求方式 url : "MyHandle.jsp?flags=userLoginCheck", dataType : "json", //预期服务器返回的数据类型 contentType : "application/x-www-form-urlencoded;charset=UTF-8", //返回给服务器时候的字符编码 data : data1, //发送到服务器上的数据,测试了一下传data2的话是不行的,data1与data3可以 success : function(data) { if (data.statusCode == "200"){ var pathName = window.document.location.pathname; var projectName = pathName.substring(0, pathName.substr(1).indexOf(\'/\') + 1); //console.log(projectName); window.location.href = projectName + "/http_homeWork/"+data.referer; }else if(data.statusCode == "404"){ $("#loginInf").html(data.message+\'<br/>\'); } }, error : function(data) { } }); }); }) </script> </head> <body> <form id="myForm"> <span id="loginInf" style="color:red"></span> 姓名: <input type="text" name="name" /> <br /> 密码: <input type="password" name="password" /> <br /> </form> <button id="submit">登陆</button> <div id="result"></div> </body> </html>
运行结果如下: