当前位置:网站首页>If no separation ----- > > login module nanny level source code analysis (0)

If no separation ----- > > login module nanny level source code analysis (0)

2022-06-11 03:20:00 The bright moon is always fresh

If you do not separate the source code of the login module

First, get the project running

We found that localhost There is one login Path can go idea Find this path and see what you have done
 Insert picture description here
Right click to open the project find in path
 Insert picture description here Let's click in this GetMapping
 Insert picture description here
Let's take this code out and taste it , You can see that there is a if Judge if yes Ajax request , return Json character string .
Otherwise, return to the login page

@GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response, ModelMap mmap)
    {
    
        //  If it is Ajax request , return Json character string .
        if (ServletUtils.isAjaxRequest(request))
        {
    
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\" No login or login timeout . Please login again \"}");
        }
        //  Whether to open and remember me 
        mmap.put("isRemembered", rememberMe);
        //  Whether to enable user registration 
        mmap.put("isAllowRegister", Convert.toBool(configService.getKey("sys.account.registerUser"), false));
        return "login";
    }

So how to return? Let's click on this renderString Method

Take the same code and taste it
Ouch, the data type is set to json, The character is encoded as utf-8, And the json Data output to browser , Is equivalent to json Object returned to Ajax

/** *  Render the string to the client  * * @param response  Apply colours to a drawing object  * @param string  The string to be rendered  * @return null */
    public static String renderString(HttpServletResponse response, String string)
    {
    
        try
        {
    
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
        }
        catch (IOException e)
        {
    
            e.printStackTrace();
        }
        return null;
    }

annotated
response.setContentType() Function and parameters of

response.setContentType(MIME) The role of is to enable the client browser , Distinguish different kinds of data , And according to different MIME Call different program embedded modules in the browser to process the corresponding data .

Code up

    /** *  Is to set the encoding format of the response connection  *  For example, I am like a url say : Hello , Then I will use by default UTF-8 Code acceptance . **/
    response.setCharacterEncoding("UTF-8");
     
    /** *  Set the encoding format in which the page is displayed , I'm going to set it to UTF-8 **/
    response.setContentType("text/html;charset=UTF-8");
     
    /** *  Each request is sent to the client of each request  **/
    response.geWriter().print(msg);

Why add such a judgment ?

It is to solve the project of separation of front and back , If you log in with your mobile phone in the future , The mobile phone is an independent front end , The view parser is useless . When I log in myself , write /login Show not logged in , The front end will be based on code = 1 Jump to the login page by yourself . How can the front end jump location.href = ctx + ‘index’; Just jump

//  If it is Ajax request , return Json character string .
        if (ServletUtils.isAjaxRequest(request))
        {
    
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\" No login or login timeout . Please login again \"}");
        }

I also want to see the verification code ?

Click the verification code to refresh
 Insert picture description here Also copy captchaImage Go to idea in find in path

Stick this part of the code to eat

 /** *  Verification code generation  */
    @GetMapping(value = "/captchaImage")
    public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response)
    {
    
        ServletOutputStream out = null;
        try
        {
    
            HttpSession session = request.getSession();
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            // Response tell type 
            response.setContentType("image/jpeg");

            // Get the parameter type from the request ( here type The corresponding is math type )
            String type = request.getParameter("type");
            String capStr = null;
            String code = null;
            BufferedImage bi = null;
            if ("math".equals(type))
            {
    
                // Created text type 
                String capText = captchaProducerMath.createText();
                // The generated text is "[email protected]" This step intercepts @ The previous part 
                capStr = capText.substring(0, capText.lastIndexOf("@"));
                // Take the last 7
                code = capText.substring(capText.lastIndexOf("@") + 1);

                // Create pictures from text 
                bi = captchaProducerMath.createImage(capStr);
            }
            else if ("char".equals(type))
            {
    
                capStr = code = captchaProducer.createText();
                bi = captchaProducer.createImage(capStr);
            }
            session.setAttribute(Constants.KAPTCHA_SESSION_KEY, code);
            out = response.getOutputStream();
						// Output the generated picture as a stream to the output stream 
            ImageIO.write(bi, "jpg", out);
            out.flush();

        }
        catch (Exception e)
        {
    
            e.printStackTrace();
        }
        finally
        {
    
            try
            {
    
                if (out != null)
                {
    
                    out.close();
                }
            }
            catch (IOException e)
            {
    
                e.printStackTrace();
            }
        }
        return null;
    }

Continue back to the login page
Enter the verification code to view
 Insert picture description here
Again Copy login Go find This time it is Post request

Find the code and start eating

@PostMapping("/login")
    @ResponseBody
//  Convert the object return to json Format 
    public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe)
    {
    
        // The information obtained from the front end , Encapsulate into a Shiro Username password token object in 
        // The token object also implements rememberMe Remember my function 
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        //Subject yes Shiro The user mechanism of , Used for security verification and other functions 
        // In order to get Subject, We usually use SecurityUtils Tool class 
// package org.apache.shiro;  Tool class of 
// package org.apache.shiro.subject;
        Subject subject = SecurityUtils.getSubject();
        try
        {
    

            // User authentication , An error will throw an exception AuthenticationException
            // The specific exception is subject Implementation class of DelegatingSubject To be specified in 
            subject.login(token);
            // Call the parent class BaseController Returned successfully success Method 
            return success();
        }
        // Verification code error exception 
        catch (AuthenticationException e)
        {
    
            String msg = " Wrong user or password ";
            // Determine if there are other mistakes 
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
    
                // If there is , Replace with this error 
                // For example, the verification code is wrong 
                msg = e.getMessage();
            }
            // Return the error message to the front end 
            //@ResponseBody
            //error The type is AjaxResult, Its essence is a hashMap
            return error(msg);
        }
    }

It is found here that direct calls return success(); Let's go in and have a look

 /** *  Return to success  */
    public AjaxResult success()
    {
    
        return AjaxResult.success();
    }

Point again AjaxResult Wrapper class , Class has enumeration methods

 /** *  State type  */
    public enum Type
    {
    
        /**  success  */
        SUCCESS(0),
        /**  Warning  */
        WARN(301),
        /**  error  */
        ERROR(500);
        private final int value;

        Type(int value)
        {
    
            this.value = value;
        }

        public int value()
        {
    
            return this.value;
        }
    }

Obviously return success(); No view parser is used The jump is judged at the front end

Let's follow login.html
Take a brief look at how you log in How the request is sent
Oh, I can't find it , It doesn't matter. Let's go into login.js Look for

As the old rule, stick it out and eat it

function login() {
    
    $.modal.loading($("#btnSubmit").data("loading"));
    // Get account password   Eliminate spaces 
    var username = $.common.trim($("input[name='username']").val());
    var password = $.common.trim($("input[name='password']").val());
    // Get the value of the verification code 
    var validateCode = $("input[name='validateCode']").val();
    var rememberMe = $("input[name='rememberme']").is(':checked');
    $.ajax({
    
        type: "post",
        //var ctx = [[@{/}]];  stay index.html There is a definition in 
        url: ctx + "login",
        // Pass these four to   The control layer login page   Buckle out the data and package it into objects to the back end 
        data: {
    
            "username": username,
            "password": password,
            "validateCode": validateCode,
            "rememberMe": rememberMe
        },
        success: function(r) {
    
            // Judge whether the status code is equal to 0
            if (r.code == web_status.SUCCESS) {
    
                // Jump to the /index page 
                location.href = ctx + 'index';
            } else {
    
                // If you fail, just   Close the circle 
            	$.modal.closeLoading();
            	// Trigger update verification code 
            	$('.imgcode').click();
            	// The verification code content is cleared 
            	$(".code").val("");
            	// Pop up login failed 
            	$.modal.msg(r.msg);
            }
        }
    });
}

Add js Characteristics of A page cited 8 individual js Equivalent to 8 individual js Write in a page that can call each other

Login here has been successful

原网站

版权声明
本文为[The bright moon is always fresh]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020554363278.html