SpringBoot realizes login registration (with source code)

The front end of this project is composed of html+css+vue (send request), the back end is processed by springboot, and the relevant database operation statement is mybatis-plus

        Take a look at my project summary:

Let’s talk about perfection first, because the front-end login registration interface is the previous one, so I copied it this time, and only wrote some vue in the front-end part, using v-model to bind username and password, and sending axios request, the back-end part is because I use mybatis-plus, and I didn’t write some sql statements. Of course, these sql statements are not very complicated. Friends who have time can try to write them directly, or modify them on the basis of mine. For the controller layer, it is Some logic statements, for example: when logging in, first determine whether the user exists in the database, and then compare the password if it exists; All in all, this project took less than 40 minutes, and it is generally good. For the novice Xiaobai, I think the difficult part is that there are some differences in the front-end and back-end interactions, and the data formats of the two are not uniform.

        The disadvantage is that the interface is too simple, there is no js effect, the effect is very direct, and more practice is required for vue to send requests.

First look at the effect of the main interface after the project is running:

The login interface is as follows:

The registration interface is as follows:

 

The project directory structure is as follows:

 

1. The design of the table in the database

1.1 Create a table with two fields, a username (varcahr type, primary key) and a password (varchar type)

1.2 The table structure is as follows

2. The jar package (pom.xml file) that needs to be imported and related configuration settings (database information and port)

2.1 The specific relevant code of the file is as follows

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.wz</groupId>
    <artifactId>LogAndRegister</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>LogAndRegister</name>
    <description>LogAndRegister</description>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.23</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2.2 Database information and port

server:
  port: 81
spring:
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/logandregister
      username: root
      password: 111111

3. Compilation of back-end related code

 3.1 The information returned by the backend to the frontend is encapsulated in the R class



@Data
public class R<T> {

    private Integer code; //编码:1成功,0和其它数字为失败

    private String msg; //错误信息

    private T data; //数据

    private Map map = new HashMap(); //动态数据

    public static <T> R<T> success(T object) {
        R<T> r = new R<T>();
        r.data = object;
        r.code = 1;
        return r;
    }

    public static <T> R<T> error(String msg) {
        R r = new R();
        r.msg = msg;
        r.code = 0;
        return r;
    }

    public R<T> add(String key, Object value) {
        this.map.put(key, value);
        return this;
    }

}

3.2 User entity class (that is, user information (account password))


@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String username;
    private String password;
}

3.3 Controller (control layer related code, processing the request sent by the front end)


@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @PostMapping("/login")
    public R<String> login(@RequestBody User user){
        log.info("user:{}",user);
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUsername,user.getUsername());
        User one = userService.getOne(lqw);
        System.out.println(one);
        // 查询不到用户
        if (one == null){
            return R.error("用户账号不存在");
        }
        // 密码错误
        if(!one.getPassword().equals(user.getPassword())){
            return R.error("密码错误");
        }
        return R.success("登陆成功");
    }
    @PostMapping("/register")
    public R<String> register(@RequestBody User user){
        log.info("user:{}",user);
        // 判断前端传来的数据是否正常
        if (user==null){
            return R.error("请输入注册信息");
        }
        // 判断账号是否存在
        String username = user.getUsername();
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername,username);
        User one = userService.getOne(lambdaQueryWrapper);
        if (one!=null){
            return R.error("用户账号已注册");
        }
        // 二者都满足则以下
        userService.save(user);
        return R.success("注册成功");

    }

}

3.4 Mapper layer related code


@Mapper
public interface UserMapper extends BaseMapper<User> {
}

3.5 Defined Service interface code


public interface UserService extends IService<User> {
}

3.6 Implement the implementation class of the Service interface

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}

4. Front-end related code

4.1 Login interface login.html (including vue sending request)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>login</title>
    <link href="css/login.css" rel="stylesheet">
</head>

<body>
<div id="loginDiv">
    <form  id="form" >
        <h1 id="loginMsg">LOGIN IN</h1>
        <p>Username:<input id="username" name="username" type="text" v-model="userName"></p>
        <p>Password:<input id="password" name="password" type="password" v-model="passWord"></p>

        <div id="subDiv">
            <input type="submit" class="button" value="login up" @click="login">
            <input type="reset" class="button" value="reset" >
            <a href="register.html">没有账号?点击注册</a>
        </div>
    </form>
</div>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
    var app = new Vue({
        el: "#loginDiv",
        data: {
            userName: "",
            passWord: "",
        },
        methods: {
            login:function (){
                console.log(this.userName,this.passWord);
                axios.post('http://localhost:81/user/login',
                    {
                    username: this.userName,
                    password: this.passWord,
                }).then( resp=> {
                    console.log(resp)
                    if (resp.data.code == '1') {
                        window.location.href = 'loginSuccess.html';
                    }else {
                        alert("账号或密码错误");
                        this.userName='';
                        this.passWord='';
                        }
                    })
                }
        }
    })
</script>
</body>
</html>

4.2 Registration interface register.html (including vue sending request)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>欢迎注册</title>
    <link href="css/register.css" rel="stylesheet">
</head>
<body>

<div class="form-div">
    <div class="reg-content">
        <h1>欢迎注册</h1>
        <span>已有帐号?</span> <a href="login.html">登录</a>
    </div>
    <form id="reg-form">

        <table>

            <tr>
                <td>用户名</td>
                <td class="inputs">
                    <input name="username" type="text" id="username" v-model="userName">
                    <br>
                    <span id="username_err" class="err_msg" style="display: none">用户名不太受欢迎</span>
                </td>

            </tr>

            <tr>
                <td>密码</td>
                <td class="inputs">
                    <input name="password" type="password" id="password" v-model="passWord">
                    <br>
                    <span id="password_err" class="err_msg" style="display: none">密码格式有误</span>
                </td>
            </tr>

        </table>

        <div class="buttons">
            <input value="注 册" type="submit" id="reg_btn" @click="register">
        </div>
        <br class="clear">
    </form>

</div>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
    var app = new Vue({
        el: "#reg-form",
        data: {
            userName: "",
            passWord: "",
        },
        methods: {
            register: function () {
                console.log(this.userName, this.passWord);
                axios.post('http://localhost:81/user/register',
                    {
                        username: this.userName,
                        password: this.passWord,
                    }).then(resp => {
                    console.log(resp)
                    if (resp.data.code == '1') {
                        alert(resp.data.data);
                        window.location.href = 'login.html';
                    } else {
                        console.log(resp.data.data);
                        alert(resp.data.data);
                        this.userName = '';
                        this.passWord = '';
                    }
                })
            }
        }
    })
</script>
</body>
</html>

5. Project summary

        Let’s talk about perfection first, because the front-end login registration interface is the previous one, so I copied it this time, and only wrote some vue in the front-end part, using v-model to bind username and password, and sending axios request, the back-end part is because I use mybatis-plus, and I didn’t write some sql statements. Of course, these sql statements are not very complicated. Friends who have time can try to write them directly, or modify them on the basis of mine. For the controller layer, it is Some logic statements, for example: when logging in, first determine whether the user exists in the database, and then compare the password if it exists; All in all, this project took less than 40 minutes, and it is generally good. For the novice Xiaobai, I think the difficult part is that there are some differences in the front-end and back-end interactions, and the data formats of the two are not uniform.

        The disadvantage is that the interface is too simple, there is no js effect, the effect is very direct, and more practice is required for vue to send requests.

Friends in need can private message me in the background to send the source code, the code text is not easy, friends can like it! ! !

        

Guess you like

Origin blog.csdn.net/m0_64238843/article/details/130954563