vue+springboot realizes login function

vue+springboot realizes login function

This article example shares the specific code of vue+springboot to realize the login function for your reference. The specific content is as follows

1. Implementation of login function

The code to submit the form is as follows:

async submitForm(user) {
        this.$refs[user].validate((valid) => {
               if(valid){
                        alert("user");
                        this.$axios.post("http:localhost:8087/user/login?code="+this.code,user).then(res => {
                            alert("success")
                             if(res.data.state){
                                 alert(res.data.msg+"Login successful, about to jump to the home page......");
                             }
                             else{
                                 alert(res.data.msg);
                             }
                        });
                    }
                    else{
                        return false;
           }
   });
},

It was a blow to the head and my head was buzzing.

This thing buzzed for several days and was finally implemented by me using a relatively stupid code. The specific idea is as follows:

First, I get the real verification code of the current verification code image in the background and pass it to the front end:

if (valid) {
        console.log(this.user);
         this.$axios.get("http://localhost:8087/user/getCode").then(res => {
                  let tcode = res.data.toLowerCase();
                  if (tcode == this.code) {
                                verify(this.user);
                            } else {
                                alert('Verification code error!');
                            }
                        });
                    }

The verify in the middle is where I verify the username and password of the user logging in. The verification code first generates a four-digit verification code and then converts it into a string in base64 format, and finally passes it to the front end, and the back end returns the string code.

@GetMapping("/getCode")
    @ApiOperation(value="Get verification code", notes="Get the verification code from the backend and send it to the frontend")
    public String getCode(HttpServletRequest request){
        String key = (String)request.getServletContext().getAttribute("code");
        log.info("key:[{}]",key);
        return key;
    }

I analyzed that the reason why the front end of the login module failed to pass values ​​to the back end was because the front end only had a username and password, and then I mistakenly thought that a form with only a username and password could form an object, which led to the form being forced to be converted into an object and passed to the back end. This caused an endless loop and I was stuck on this problem for a long time. Previously, the username, password and verification code were passed to the backend and were stuck there. I first get the verification code from the back end and compare it on the front end to see if it is correct. Then I pass the username and password entered by the user to the back end to search the database for the user with the corresponding username. If the user can be found, it means that the user exists, otherwise the user exists. Next, compare whether the password entered by the user is consistent with the password stored in the database. If they are consistent, it returns true and the login is successful. Otherwise, it fails. The specific implementation code is as follows:

//UserController
 @PostMapping("/login")
    @ApiOperation(value = "Login to the system", notes = "Login to the employee management system")
    public Map<String,Object> login(@RequestParam String Name,@RequestParam String Pwd){
        System.out.println(Name+" "+Pwd);
        Map<String,Object> map = new HashMap<>();
        try{
            User userdb = userService.login(Name,Pwd);
            map.put("state",true);
            map.put("msg","Login successful");
            map.put("user",userdb);
        }catch(Exception e){
            e.printStackTrace();
            map.put("state",false);
            map.put("msg",e.getMessage());
        }
        log.info("[{}]",map.toString());
        return map;
    }
//UserServiceImpl
 @Override
    public User login(String Name,String Pwd) {
        User userDB = userMapper.selectByName(Name);
        if(!ObjectUtils.isEmpty(userDB)){
            if (userDB.getPwd().equals(Pwd)) {
                return userDB;
            }
            else{
                throw new RuntimeException("Incorrect password");
            }
        }
        else{
            throw new RuntimeException("User does not exist");
        }
    }
//UserMapper.java
User selectByName(String name);
<!--UserMapper.xml-->
 <select id="selectByName" parameterType="String" resultType="com.sunset.system.entity.User">
        select Id,Name,Age,Sex,Pwd,Dept,Salary
        from user where Name = #{name}
</select>

During the coding process, I encountered a small episode where Name = "#{name}" caused an error in the database search. I hope that people who read this article can avoid this pitfall.
In this way, the backend logic is implemented, and the following is the frontend logic:

async function verify(userinfo) {
      const {data: res} = await verifyUser(userinfo);
      console.log(res);
          if (res.state == true) {
               _this.$message({
                 title: "Verification successful",
                 message: "Welcome to the employee management system",
                  type: "success"
            });
      window.location.href = "http://www.baidu.com";
      //await _this.$router.push("http://www.baidu.com");
       } else {
           _this.$message({
            title: "Verification failed",
         message: res.msg,
          type: "error"
       })
       return false;
     }
}

Here we use axios post request, the specific path is projectName.src.api to create a new user.js file

export const verifyUser = (user) => {
    return request({
        url: "/user/login",
        method: 'post',
        params: {
            Name: user.Name,
            Pwd: user.Pwd
        }
    })
}

In addition, you need to configure request.js, the file path is projectName.src.utils

import axios from 'axios'

const instance = axios.create({
  baseURL: 'http://localhost:8080', //Port of the backend project timeout: 10000,
  headers: {'X-Custom-Header': 'foobar'}
});

export default instance;

If you have other logical questions, welcome to discuss.

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Springboot+VUE front-end and back-end separation to realize the epidemic prevention platform JAVA
  • Springboot+vue realizes verification code function
  • Cross-domain issues in front-end and back-end separation of Vue+SpringBoot
  • SpringBoot+VUE implements data table practice
  • Realizing garbage classification management system based on springboot+vue
  • SpringBoot+MyBatisPlus+Vue front-end and back-end separation project quick construction process (front-end chapter)
  • SpringBoot+MyBatisPlus+Vue front-end and back-end separation project quick construction process (back-end)
  • Springboot+vue production background management system project

<<:  MySQL query statement simple operation example

>>:  Detailed explanation of the redirection configuration and practice of Rewrite in Nginx

Recommend

vue uses Ele.me UI to imitate the filtering function of teambition

Table of contents Problem Description The general...

How to make ApacheBench support multi-url

Since the standard ab only supports stress testin...

Detailed explanation of the basic use of react-navigation6.x routing library

Table of contents react-native project initializa...

Nginx Linux installation and deployment detailed tutorial

1. Introduction to Nginx Nginx is a web server th...

Summary of Seven Basic XHTML Coding Rules

1. All tags must have a corresponding end tag Prev...

MySQL uninstall and install graphic tutorial under Linux

This is my first time writing a blog. I have been...

CentOS8 installation tutorial of jdk8 / java8 (recommended)

Preface At first, I wanted to use wget to downloa...

How to use CSS media query aspect-ratio less

CSS media query has a very convenient aspect rati...

Summary of new usage of vi (vim) under Linux

I have used the vi editor for several years, but ...

IDEA2021 tomcat10 servlet newer version pitfalls

Because the version I used when I was learning wa...

Steps to restore code from a Docker container image

Sometimes the code is lost and you need to recove...

Implementation code for using mongodb database in Docker

Get the mongo image sudo docker pull mongo Run th...

Vue scaffolding learning project creation method

1. What is scaffolding? 1. Vue CLI Vue CLI is a c...