weixin_33713350 2017-08-02 19:33 采纳率: 0%
浏览 16

如何使用Ajax检查登录?

I am a student who has just studied Ajax.

I have been constantly worried, but I have not been able to solve the problem.

So, I want to get some advice from you.

First, I will show the loginPage.jsp code and the MemberController.java code and the MemberService.java code.

It is loginPage.jsp code.

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/swiper.min.css">
<link rel="stylesheet" href="css/loginPage.css">
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="js/swiper.jquery.min.js"></script>
<title>Insert title here</title>
</head>
<body>
<jsp:include page="header.jsp" />
<div class="loginPage_main">
    <div class="pageName">
        <img class="pageName_image" src="images/greeting_title.jpg">
        <div class="pageName_explanation">
            <p>로그인</p>
        </div>
    </div>
    <div class="location">
    </div>
    <div class="loginForm_area">
        <div class="hidden_area">
            <div class="img_lock_area">
                <img src="images/lock.png" class="img_lock">
            </div>
            <form action="loginOK.do" id="login_frm" name="frm" method="post" onsubmit="return checkValue()">
                <div class="input_zone">
                    <div class="input_id">
                        <span>&nbsp;&nbsp;ID</span><input type="text" placeholder="아이디를 입력하세요" style="width:280px;margin-left: 10px;" name="id">
                    </div>  
                    <div class="input_pw">
                        <span>PW</span><input type="password" placeholder="비밀번호를 입력하세요" style="width:280px;margin-left: 10px;" name="pw">
                    </div>
                </div>
            </form>     
                <div class="loginBtn" onclick="document.getElementById('login_frm').onsubmit();">
                    <div style="margin-top: 22px;">
                        <span class="loginOK">Login</span>
                    </div>
                </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    function checkValue() 
    {
        var form = document.frm;

        if(!form.id.value || !form.pw.value)
        {
            alert('아이디 혹은 비밀번호를 입력하세요.');
            return false;
        }

        $.ajax
        ({
            type: 'POST',
            url: 'loginOK.do',
            success: function()
            {
                alert('success');
            },
            error: function()
            {
                alert('error');
            }
        })
    }       
</script>
</body>
</html>

It is MemberController.java code.

package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import service.MemberService;

@Controller
public class MemberController 
{
    @Autowired
    public MemberService mService;


    // 로그인
    // 전송된 ID,PW값과 DB에 있는 ID,PW값 비교
    // 맞으면 alert 창으로 " 로그인 성공 " 메세지 표출 + mainPage 이동
    // 틀리다면 alert 창으로 " 로그인 실패 " 메세지 표출 + loginPage로 리다이렉트
    @RequestMapping("loginOK.do")
    public String login(String id, String pw,HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException 
    {
        HashMap<String, Object> loginIdentify = mService.login(id,pw);

        System.out.println("ID is : " +  id + " / " + "PW is : " + pw);

        if(loginIdentify != null)
        {
            System.out.println("loginIdentify is  true : " + loginIdentify);

            session.setAttribute("id", id);
            session.setAttribute("pw", pw);

            /* 
            - 오류로 인한 일시 보류 -             
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();

             writer.println("<script type='text/javascript'>");
             writer.println("alert('로그인 성공!');");
             writer.println("</script>");
             writer.flush();
             */
        }
        else
        {
            System.out.println("loginIdentify is false : "  + loginIdentify);

            /*      
            - 오류로 인한 일시 보류 -         
             response.setCharacterEncoding("UTF-8");
             PrintWriter writer = response.getWriter();

             writer.println("<script type='text/javascript'>");
             writer.println("alert('로그인 실패!');");
             writer.println("</script>");
             writer.flush();
             */

            return "redirect:move_loginPage.do";
        }
        return "redirect:main.do";
    }


    // 로그아웃
    // 세션과 쿠키 제거 + mainPage로 리다이렉트
    @RequestMapping("logout.do")
    public String logout(HttpSession session, HttpServletResponse response)
    {
        session.removeAttribute("id");

        Cookie cookie = new Cookie("id", null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        // 세션 삭제 확인
        System.out.println("session is delete It's really? : " + session.getAttribute("id"));

        return "redirect:main.do";
    }
}

It is MemberService.java code.

package service;

import java.util.HashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;


import dao.IMemberDAO;
import model.Member;

@Service
public class MemberService  
{
    @Autowired
    private IMemberDAO memberDao;

    public HashMap<String, Object> login(String id,String pw)
    {
        HashMap<String, Object> result = memberDao.selectOne(id);

        System.out.println(result);

        if(result != null)
        {
            String opwd = (String) result.get("pw");

            if(opwd.equals(pw))
            {
                return result;
            }
            else
            {
                return null;
            }
        }
        else
        {
            return null;
        }
    }
}

When the form tag is executed, the ID value and PW value entered are compared with the ID value and PW value stored in the DB.

If the values ​​match, go to the main page.

If the values ​​do not match, you will not be able to log in without reloading the page! I want to print a message. How can I get it to work the way I want?

I do not know where to start.... I need your help vigorously. Please advice to me your plan.

  • 写回答

1条回答 默认 最新

  • 笑故挽风 2017-08-02 20:08
    关注

    You're almost there.

    Uncomment the code in MemberController.java that uses response to send data back to the client JavaScript. Something like—

    PrintWriter writer = response.getWriter();
    writer.println("login succeeded");
    writer.flush();
    

    —and similarly for the failure case.

    Then, in loginPage.jsp, read the first argument in $.ajax's success function to get that same data back:

    $.ajax
        ({
            type: 'POST',
            url: 'loginOK.do',
            success: function(returnData)
            {
                console.log(returnData); // <---
            },
            error: function()
            {
                alert('error');
            }
        })
    

    That way, the client will know whether the login succeeded or not, and you can call the appropriate JavaScript functions to open a different page, show an error, clear the password box, or whatever you want to do.


    Tangential application security critiques:

    • I hope you're using HTTPS. If not, user credentials are easy for an attacker to steal.
    • It seems you are storing your users' passwords in plain text in your database. Consider salting them to protect them in case your database is compromised.
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能