团队冲刺-个人部分9

昨天的成就:

创建了一些虚拟用户的基本信息,用于登录功能的测试。

遇到的问题:

用户登录时,从后端将用户类对象的转换为Json字符串时,如果将用户的passwd设为null(为了保证不会暴露用户的密码)则在用户再次登陆时就会导致验证该对象的passwd为空,抛出空指针异常。

解决方法:

将需要传递的用户的信息保存到map对象中,再进行传输。

今天的任务:

实现基本的登录功能,保证用户登陆时能够将其登录信息在浏览器中持久存在。

js(Ajax)代码:

var id = document.getElementById('username');
var passwd = document.getElementById('passwd');
​
function login() {
    var xmlhttlp
    if (window.XMLHttpRequest) {
        xmlhttlp = new XMLHttpRequest();
    } else {
        xmlhttlp = new ActiveXObject('Microsoft.XMLHTTP');
    }
    xmlhttlp.onreadystatechange = function () {
        console.log(xmlhttlp.readyState);
        console.log(xmlhttlp.status);
        if (xmlhttlp.readyState == 4 && xmlhttlp.status == 200) {
            var status = xmlhttlp.responseText;
            if (status == -1) {
                alert('账号或密码错误');
            } else {
                sessionStorage['user'] = status;
                window.location.href = './index.jsp';
            }
        }
    }
    xmlhttlp.open('POST', 'UserServlet?type=0&username=' + id.value + '&passwd=' + passwd.value, true);
    xmlhttlp.send();
}
​
function checkInfo() {
    // console.log(id.textContent);
    if (id.value == '') {
        alert('请输入账号');
        return -1;
    }
    if (passwd.value == '') {
        alert('请输入密码');
        return -2;
    }
    return 0;
}
​
function submit() {
    if (checkInfo() == 0) {
        login();
    }
}
​
document.getElementById('submit').onclick = function () {
    submit();
}

Java(Servlet)部分:

  
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
       String requestType = request.getParameter("type");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        String status = "";
        if ("0".equals(requestType))
        {
            String username = request.getParameter("username");
            String passwd = request.getParameter("passwd");
            tempUser = UserUtils.getPasswd(username);
            if (tempUser!=null && tempUser.getPasswd().equals(passwd))
            {
//              tempUser.setPasswd(null);
//                将用户信息转换成Json字符串传递给前端
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id",tempUser.getId());
                map.put("name",tempUser.getName());
              status = JsonUtils.getGson().toJson(map);
            } else
            {
//                登陆失败返回的信息
               status = "-1";
            }
​
        } 
    }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
​
原文地址:https://www.cnblogs.com/MXming/p/14762516.html