ajax實現用戶登錄,退出,java作後端

最近http老師佈置了個任務,用cookie完成登錄,退出。Http老師講的是node.js寫後端,因爲本身仍是擅長java些,仍是用Java作了。javascript

之前跟着教程寫過一個網站,當初是用jsp+servlet+javabean去實現的,如今想結合json和ajax實現一下,搞了一下午,遇到了些問題,總結一下html

1.當初在servlet中用cookie存儲中文並無出現亂碼問題,可能進行了封裝吧。我在Java中用cookie去存儲用戶名出現了中文亂碼問題,報錯了。。查閱資料使用URLEncoder.encode進行編碼java

2.編碼以後使用js取cookie出現中文亂碼問題,javascript中有個函數進行解碼操做:decodeURIComponent()node

3.學習並掌握js取cookie,刪除cookie的方法jquery

代碼以下:

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>
    &nbsp;&nbsp;&nbsp;
    <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>

運行結果以下:

相關文章
相關標籤/搜索