SSM development book review network 22: realize the member login function; (the core of this blog is to be familiar with the processing logic of logging in.)

explain:

(1) The main content of this blog: realize the member login function; (including front-end and back-end business logic of member login)

(2) Some notes of this blog:

● in front[ (12) Muke OA system (Mybatis project case, more important!) ]In, member login has also been realized; You can quickly refer to the content there and compare it with this section to help understand [login, this kind of business logic]; (although the complexity of the two is different, take a look. It won't take long)

(3) This blog, Login function development process: [first determine the front-end file login.ftl of the login page and write the login front-end file] → [then write the Controller method and set the entry method to access the login.ftl login page, that is, set the url to access login.ftl] → [then set the login hyperlink on the home page to point to the url we set in the previous step] → [write the Service of the login function, mainly write the login processing logic] → [write the Controller method of the login function, receive the login request on the login page, call the Service logic, and return the login result to the login.ftl login page] → [if the login is successful, don't forget to save the information of the current login user into the Session object; in this way, after the login is successful, we can directly get the data where the current login user needs to be displayed];

(4) In fact, the most important thing in this article is to be familiar with [login, this kind of business logic]; Including the points needing attention and habitual actions when handling login;

catalogue

1: The login page front-end file login Introduction to FTL;

2: Login function background logic;

1. In the MemberController class: develop the [entry method for accessing the login page]; (that is, the access url of the login.ftl login page for development)

2. In the MemberService interface, define a login method: checkLogin() method;

3. In the MemberServiceImpl implementation class, the method to implement login: checkLogin() method;

4. Write a login processing method checkLogin() in the MemberController to receive the request from the front end and call the logic defined in the Service;

Start Tomcat and observe the effect;

Supplement 1: after successful login, save the [Member user object returned by the Service layer] in the Session; Then, we can get the information of the current login user where needed;

Supplement 2: after the user logs in successfully and jumps to the default home page, the "member name of the currently logged in user" will be displayed in the upper right corner of the page; (in fact, it is to obtain the user information stored in Supplement 1) (the and principle behind it is that FreeMarker can also go to the data in the Session object)

Start Tomcat and observe the effect;

3: Temporary Summary: when [back end returns JSON], [data is placed in session object], [data is placed in ModelAndView]: analysis of front-end value; (temporary Summary. If you have new understanding in the future, you can revise and supplement it at any time)

1. When the data is placed in ModelAndView: in fact, the data is placed in the HttpServletRequest object; At the front end, we can use FreeMarker to retrieve;

2. When the data is placed in the Session object: in fact, the data is placed in the HttpServletRequest field; At the front end, we can also directly use FreeMarker to get it;

3. JSON data returned from the back end: in this case, it generally corresponds to page ajax requests (such as login, registration, local page refresh), cross interface value transfer, etc., which do not involve page Jump; (that is, at this time, our data is only JSON, which is only in the response; the data is not in the three scope objects;)

1: The login page front-end file login Introduction to FTL;

Introduce the login page login ftl;

login.ftl:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Member login-Muke Book Review Network</title>
    <meta name="viewport" content="width=device-width,initial-scale=1.0, maximum-scale=1.0,user-scalable=no">
    <link rel="stylesheet" href="http://cdn.itlaoqi.com./resources/bootstrap4/css/bootstrap.css">
    <link rel="stylesheet" href="./resources/raty/lib/jquery.raty.css">

    <script src="http://cdn.itlaoqi.com./resources/jquery.3.3.1.min.js"></script>
    <script src="http://cdn.itlaoqi.com./resources/bootstrap4/js/bootstrap.min.js"></script>
    <style>
        .container {
            padding: 0px;
            margin: 0px;
        }

        .row {
            padding: 0px;
            margin: 0px;
        }

        .col- * {
            padding: 0px;
        }

        .description p {
            text-indent: 2em;
        }

        .description img {
            width: 100%;
        }

    </style>

</head>
<body>
<!--<div style="width: 375px;margin-left: auto;margin-right: auto;">-->
<div class="container ">
    <nav class="navbar navbar-light bg-white shadow">
        <ul class="nav">
            <li class="nav-item">
                <a href="/">
                    <img src="https://m.imooc.com/static/wap/static/common/img/logo2.png" class="mt-1"
                         style="width: 100px">
                </a>
            </li>
        </ul>
    </nav>


    <div class="container mt-2 p-2 m-0">
        <form id="frmLogin">
            <div class="passport bg-white">
                <h4 class="float-left">Member login</h4>
                <h6 class="float-right pt-2"><a href="/register.html">Member registration</a></h6>
                <div class="clearfix"></div>
                <div class="alert d-none mt-2" id="tips" role="alert">

                </div>

                <div class="input-group  mt-2 ">
                    <input type="text" id="username" name="username" class="form-control p-4" placeholder="enter one user name"
                           aria-label="Username" aria-describedby="basic-addon1">
                </div>

                <div class="input-group  mt-4 ">
                    <input id="password" name="password" class="form-control p-4" placeholder="Please input a password" type="password"
                           aria-describedby="basic-addon1">
                </div>

                <div class="input-group mt-4 ">
                    <div class="col-5 p-0">
                        <input type="text" id="verifyCode" name="vc" class="form-control p-4" placeholder="Verification Code">
                    </div>
                    <div class="col-4 p-0 pl-2 pt-0">
                        <img id="imgVerifyCode" src="/verify_code"
                             style="width: 120px;height:50px;cursor: pointer">
                    </div>

                </div>

                <a id="btnSubmit" class="btn btn-success  btn-block mt-4 text-white pt-3 pb-3">Ascend&nbsp;&nbsp;&nbsp;&nbsp;record</a>
            </div>
        </form>

    </div>
</div>

<script>
    function showTips(isShow, css, text) {
        if (isShow) {
            $("#tips").removeClass("d-none")
            $("#tips").hide();
            $("#tips").addClass(css);
            $("#tips").text(text);
            $("#tips").fadeIn(200);
        } else {
            $("#tips").text("");
            $("#tips").fadeOut(200);
            $("#tips").removeClass();
            $("#tips").addClass("alert")
        }
    }
    function reloadVerifyCode(){
        $("#imgVerifyCode").attr("src", "/verify_code?ts=" + new Date().getTime());
    }
    $("#imgVerifyCode").click(function () {
        reloadVerifyCode();
    });

    $("#btnSubmit").click(function () {
        var username = $.trim($("#username").val());
        var regex = /^.{1,10}$/;
        if (!regex.test(username)) {
            showTips(true, "alert-danger", "Please enter the correct format for user name (1)-10 Bit)");
            return;
        } else {
            showTips(false);
        }

        var password = $.trim($("#password").val());

        if (!regex.test(password)) {
            showTips(true, "alert-danger", "Please enter the correct password format (1)-10 Bit)");
            return;
        } else {
            showTips(false);
        }

        $btnReg = $(this);

        $btnReg.text("Processing...");
        $btnReg.attr("disabled", "disabled");
        $.ajax({
            url: "/check_login",
            type: "post",
            dataType: "json",
            data: $("#frmLogin").serialize(),
            success: function (data) {
                console.info(data);
                if (data.code == "0") {
                    window.location = "/?ts=" + new Date().getTime();
                } else {
                    showTips(true, "alert-danger", data.msg);
                    reloadVerifyCode();
                    $btnReg.text("Sign in");
                    $btnReg.removeAttr("disabled");
                }
            }
        });
        return false;
    });


</script>
</body>
</html>

explain:

(1) Script content description 1;

(2) Script content description 2;

 

Front end landing page login FTL is ready. Our main task is to complete the background logic of login function as required;

2: Login function background logic;

1. In the MemberController class: develop the [entry method for accessing the login page]; (that is, the access url of the login.ftl login page for development)

explain:

(1) The reason is that the url should be attached html, this is because: the login page of the system is a place that can be accessed by the outside world After html, it will help Baidu, Google and other search engines to capture, and help the marketing and publicity of the website; (in)[ SSM develops book review network 20: apply [Kaptcha verification code function] to the registration module; ]First encountered in)

(2) Then, start Tomcat, and we can access the login page through [localhost/login.html];

2. In the MemberService interface, define a login method: checkLogin() method;

 

3. In the MemberServiceImpl implementation class, the method to implement login: checkLogin() method;

explain:

(1) The logic of this method is very clear: [first query the database according to the user name entered by the user] → [if it is not found, it means that the user does not exist] → [if it is found, but the password is wrong, it means that the password is wrong] → [if everything is OK, return the found Member object];

4. Write a login processing method checkLogin() in the MemberController to receive the request from the front end and call the logic defined in the Service;

package com.imooc.reader.controller;

import com.imooc.reader.entity.Member;
import com.imooc.reader.service.MemberService;
import com.imooc.reader.service.exception.BussinessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * member Member Controller
 */
@Controller
public class MemberController {
    @Resource
    private MemberService memberService;

    @PostMapping("check_login")
    @ResponseBody
    public Map checkLogin(String username, String password, String vc, HttpSession session) {
        Map result = new HashMap();
        //First, get the verification code stored in the back end from the Session object
        String verifyCode = (String) session.getAttribute("kaptchaVerifyCode");
        //If [no verification code entered at the front end] or [no verification code in the current Session] or [the verification code entered at the front end and the verification code at the back end are inconsistent after ignoring case]: the verification fails;
        if (vc == null || verifyCode == null ||!vc.equalsIgnoreCase(verifyCode)) {
            result.put("code", "VC01");
            result.put("msg", "Verification code error");
        } else {
            try {
                Member member = memberService.checkLogin(username, password);
                result.put("code", "0");
                result.put("msg", "success Processing succeeded");
            } catch (BussinessException ex) {
                ex.printStackTrace();
                result.put("code", ex.getCode());
                result.put("msg", ex.getMsg());
            }
        }
        return result;
    }
}

explain:

(1) A lot of the content here is the same as the previous one[ SSM development book review network 21: complete the member registration function; ]The contents in the articles are very similar, which have been mentioned in the previous articles; There is no repetition here;

(2) Just emphasize one point: like HttpServletRequest, just write the HttpSession object in the method parameters directly, and Spring will automatically inject it for us;

Start Tomcat and observe the effect;

If the user name, password and verification code entered are correct: it is found that the login is OK and jumps to the default home page (i.e. root path);

Supplement 1: after successful login, save the [Member user object returned by the Service layer] in the Session; Then, we can get the information of the current login user where needed;

Supplement 2: after the user logs in successfully and jumps to the default home page, the "member name of the currently logged in user" will be displayed in the upper right corner of the page; (in fact, it is to obtain the user information stored in Supplement 1) (the and principle behind it is that FreeMarker can also go to the data in the Session object)

explain:

(1) You can see that the login on the home page is a hyperlink, and its address corresponds to the [/ login.html] login page; That is, when we click this login button, it will jump to the login page;  

(2) Content description;

(3) Obviously, when we save the data in ModelAndView, it is actually stored in the HttpServletRequest object. We can get it through FreeMarker at the front end; Then, if we store the data in the Session object, we can also get it through the FreeMarker at the front end;

(4)<#if loginMember??> of This means that if loginmember exists, it will enter this judgment structure; For FreeMarker syntax, please refer to[ FreeMarker 4: basic syntax of FreeMarker: Branch judgment ]And nearby articles;

Start Tomcat and observe the effect;

So far, the login function is realized; Next, start [user related operations]; Such as changing reading status, publishing short comments and praising short comments;   

3: Temporary Summary: when [back end returns JSON], [data is placed in session object], [data is placed in ModelAndView]: analysis of front-end value; (temporary Summary. If you have new understanding in the future, you can revise and supplement it at any time)

1. When the data is placed in ModelAndView: in fact, the data is placed in the HttpServletRequest object; At the front end, we can use FreeMarker to retrieve;

At the front end, ftl can be directly accessed;

Have the energy to study[ Why is the return value of ModelAndView used in spring MVC stored in the request field [source code analysis]_ CSDN blog];

2. When the data is placed in the Session object: in fact, the data is placed in the HttpServletRequest field; At the front end, we can also directly use FreeMarker to get it;

3. JSON data returned from the back end: in this case, it generally corresponds to page ajax requests (such as login, registration, local page refresh), cross interface value transfer, etc., which do not involve page Jump; (that is, at this time, our data is only JSON, which is only in the response; the data is not in the three scope objects;)

Because JavaScript has good support for JSON, you can directly use JavaScript to get the value of JSON;

Keywords: Java Back-end SSM

Added by Slip on Mon, 10 Jan 2022 06:44:27 +0200