1. Create a Springboot project

Development tools we use IntelliJ IDEA, environment installation is not described, if the environment will not build friends, you can comment or private chat, I later in writing a chapter environment build, mysql installation article:

  1. Open IntelliJ IDEA, new Project or File -> new -> Project… ;
  2. Select Spring Initializr, select the corresponding Project SDK and click Next. If the Project SDK is not optional, please install the SDK first.

As shown aboveGroupChange to your own registration, recommend domain name + project name, for examplewww.td0f7.cn.springboot01 ArtifactFor your own project name, you can underline it like spring_boot_demotypeIs the package management mode. If you do not know the two modes, you are advised to use the default modeLauguageThe development language is Java by default and can be modified by yourselfPackagingIn order to package, I am used to war, so I choose WARJava VersionFor the development language version number, my native Java version number is 8, so select 8When the change is complete, clickNextA second screen appears after clicking Next

The Project Name is the Name of the Project, and you can change it to your own. The default is brought from the previous interface. You don’t need to change the Project location to your own storage path, then click Firish and wait for the loading to complete

2. Project structure introduction

In the root directory as shownpom.xmlIt’s package management, introducing some new JAR packages here, changing the SpringBoot version number, changing the packaging, etcsrc main javaIt’s where you write codeSpringBootDemoApplicationThis is the main entry of the programresourcesStore some resourcesapplication.propertiesConfig file, config port number, mysql, redis and so onstaticStatic resources, JS CSS images, etctemplatesPut the HTML interface

Other tutorials are used in detailed explanation

3. Import packages such as mysql

Since the new project does not introduce any packages, the database packages are introduced. Start by opening the pom.xml in the project root directory and adding it under the Content Dependencies node

<dependencies> <! <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope>  </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> < artifactId > mybatis - spring - the boot - starter < / artifactId > < version > 1.3.2 < / version > < / dependency > < the dependency > <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.6</version> </dependency> <! <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>Copy the code

Lombok is an entity class toolkit that automatically adds get set methods to mysql databases. Org.mybatis. Spring. Easier to manipulate database Gson is the object to JSON string utility class

4. Modify the database configuration file

Open the project root directory SRC -> main -> resources -> application.properties file

Spring.datasource. Url = JDBC :mysql://mysqlip: port /mysql? UseUnicode = true&characterEncoding = utf-8 & serverTimezone = UTC&useSSL = true spring. The datasource. The username = database account Spring. The datasource. Password = password databaseCopy the code

Such as

Spring. The datasource. Url = JDBC: mysql: / / 127.0.0.1 / springboot? useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true spring.datasource.username=springboot spring.datasource.password=wangzhongCopy the code

The default mysql port is 3306. If the port number has not been changed, the port number of spring. Datasource

5. Create the mysql database user table

CREATE TABLE `springboot`.`user` ( `id` INT NOT NULL AUTO_INCREMENT , `user` VARCHAR(30) NOT NULL , `pass` VARCHAR(30) NOT NULL , PRIMARY KEY (`id`), UNIQUE `u_user` (`user`) ENGINE = MEMORY;
Copy the code

Mysql > select * from user where username = ‘user’

This is the end of the environment, and it’s time to write code

6. Write code to implement login interface

First in SRC main Java SpringBootDemoApplication under your bag at the same level directory create mapper controller entity three package mapper store operation database code controller The code of the storage API, the API called by the foreground is the entity class corresponding to the entity storage database under this

The first step is to create the User entity class file under the Entity package


import lombok.Data;

The @data annotation will automatically add get set methods to the attributes of the entity class, which must reference the Lombok package to use
@Data
public class User {
    private int id;
    private String user;
    private String pass;
}

Copy the code

Create a UserMapper with the name of a database table +Mapper and type interface

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import www.td0f7.cn.springboot01.spring_boot_demo.entity.User;

// This annotation is required, otherwise the mapper cannot be scanned
@Mapper
public interface UserMapper {
    / * * *@Select* #{user} represents the return value of the user parameter * @ in this method login is query, because the user login account is unique, all return types are a user object rather than a set */
    @Select("select * from user where user = #{user} and pass = #{pass}")
    User login(String user, String pass);
}

Copy the code

Create a UserController to provide a callable API to the outside world


import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import www.td0f7.cn.springboot01.spring_boot_demo.entity.User;
import www.td0f7.cn.springboot01.spring_boot_demo.mapper.UserMapper;

@RestController// If the return value is an object, it is automatically converted to JSON
// @requestMapping ("user"); // @requestMapping ("user")
/ / we start the web site is http://localhost:8080, to access the controller is http://localhost:8080/user
@RequestMapping("user")
public class UserController {
    @Autowired(required = false)// Automatically scan mapper files
    private UserMapper mapper;

    /** * This interface is post **@paramThe user parameter user defaults to null. DefaultValue is null *@param pass
     * @return* /
    @PostMapping("login")
    public String login(@RequestParam(value = "user", defaultValue = "") String user,
                        @RequestParam(value = "pass", defaultValue = "") String pass) {
        if (user.equals("")) return "Account must be passed";
        if (pass.equals("")) return "Password must be passed";
        User user1 = mapper.login(user, pass);
        if (user1 == null) {// If no data is found, the account does not exist
            return "Incorrect account password!";
        } else {
            return new Gson().toJson(user1);// If the login succeeds, the object is returned as a JSON string}}}Copy the code

7. Run the start test

Adding data to a database

INSERT INTO `user`(`user`.`pass`) VALUES ('wz'.'123456')
Copy the code

The data of account WZ password 123456 has been added above

Next, run the project tests

Use postman tests

Ok, login is complete!! The registration function will be released later