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

Summary of javascript date tools

let Utils = { /** * Is it the year of death? * @r...

Our thoughts on the UI engineer career

I have been depressed for a long time, why? Some t...

centos7.2 offline installation mysql5.7.18.tar.gz

Because of network isolation, MySQL cannot be ins...

How to implement Vue timer

This article example shares the specific code of ...

MySQL trigger simple usage example

This article uses examples to illustrate the simp...

Detailed explanation of nginx installation, deployment and usage on Linux

Table of contents 1. Download 2. Deployment 3. Ng...

How to add a pop-up bottom action button for element-ui's Select and Cascader

As shown in the figure below, it is a common desi...

Three ways to achieve text flashing effect in CSS3 Example code

1. Change the transparency to achieve the gradual...

Implementation and optimization of MySql subquery IN

Table of contents Why is IN slow? Which is faster...

MySql knowledge points: transaction, index, lock principle and usage analysis

This article uses examples to explain the princip...

Solve the problem of setting Chinese language pack for Docker container

If you use docker search centos in Docker Use doc...