Introduction to spring boot project

Recently, I watched a lot of spring boot teaching videos. I felt they were too long, and there was no actual combat of the project. Today, according to a blogger to write a simple user system to add, delete, modify and check, the source code can refer to the second issue of the article. This project uses Springboot+Mybatis+Mysql. The first phase only realizes the function of user login.

(1) Create a Springboot project

File > New Project > Spring Initializr. After filling in the information about the project, be sure to select the following template:

Note: generally, Maven will automatically download and rely on after the project is created. If the download is very slow (indicating that it is an external network download), Alibaba cloud image is recommended, and the configuration method is Baidu.

(2) Connect to database

The idea has the function of connecting to the database. After connecting to the database, you can get the information of the database, so you don't need to open the database server. The specific operations are as follows:

Fill in when connecting to the database:

If the connection is successful, you can see:

Preparation of configuration file for project connection to database: after the database connection, the database data needs to be imported into the project and configuration file (I prefer yml configuration, so the global configuration file application.properties Change to yml suffix) as follows:

Note: the table of the database needs to be built first, and then fill in the information and port of the database. I use the 3305 port, which is inconsistent with the default 3306.

(3) Build project structure

As MVC architecture is required for general projects, the project architecture is as follows:
Project document xin01 construction display:

Resource file resources building display:

pom configuration file display (fill in the version of mysql connection jar package):

<?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.3.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.huang</groupId>
    <artifactId>xin01</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>xin01</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.26</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
<!--            <exclusions>-->
<!--                <exclusion>-->
<!--                    <groupId>org.junit.vintage</groupId>-->
<!--                    <artifactId>junit-vintage-engine</artifactId>-->
<!--                </exclusion>-->
<!--            </exclusions>-->
        </dependency>
    </dependencies>

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

</project>

Generally, it will be created automatically. Note that there is a conflict here and a label of test is annotated.

Note: if you don't have a file created by yourself, you must not miss the file or write the wrong file name.

(4) Specific code writing

1. html writing of front-end page
error.html

<!--Login failure page-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>error</title>
</head>
<body>
<h1>Login failed!</h1>
</body>
</html>

index.html

<!--home page-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    //Hello springboot, this is the first springboot project of XXX.
</body>
</html>

login.html (this front-end page needs to submit form data, which is more important)

<!--Login page-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login</title>
</head>
<body>
<!--Implement form submission-->
<form role="form" action = "/loginIn" method="post">
    account number:<input type="text" id="name" name = "name"> <br>
    password:<input type="password" id = "password" name = "password"> <br>
    <input type="submit" id = "login" value = "login">
</form>
</body>
</html>

success.html

<!--Login success page-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>success</title>
</head>
<body>
<h1>Login succeeded!</h1>
</body>
</html>

2.UserBean class writing
UserBean

package com.huang.xin01.bean;

/*
User entity class, corresponding to the user table of the database
 */
public class UserBean {
    private int id;
    private String name;
    private String password;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "UserBean{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

3.HelloController class, LoginController class writing
HelloController

package com.huang.xin01.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/*
Home control layer
 */
@Controller
public class HelloController {
    @RequestMapping("/index")
    public String hello(){
        return "index";
    }
}

LoginController

package com.huang.xin01.controller;

import com.huang.xin01.bean.UserBean;
import com.huang.xin01.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/*
Control layer of login function
 */
@Controller
public class LoginController {
    //Call userService and put it in the container to prevent coupling
    @Autowired
    UserService userService;
    //Login page
    @RequestMapping("/login")
    public String show(){
        return "login";
    }
    //Control of forms submitted according to post
    @RequestMapping(value = "/loginIn",method = RequestMethod.POST)
    public String login(String name,String password){
        UserBean userBean = userService.loginIn(name,password);
        if(userBean!=null){
            return "success";
        }else{
            return "error";
        }

    }
}

4.UserMapper interface UserMapper.xml Profile application.yml Global configuration file writing
UserMapper

package com.huang.xin01.mapper;

import com.huang.xin01.bean.UserBean;
import org.springframework.stereotype.Repository;
/*
Dao Layer, responsible for the interface of the database, which is implemented through the Mybatis configuration file
 */
//@Repository
public interface UserMapper {
    UserBean getInfo(String name,String password);
}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<!--Dao The specific implementation of the Mybatis-->
<mapper namespace="com.huang.xin01.mapper.UserMapper">
    <select id="getInfo" parameterType="String" resultType="com.huang.xin01.bean.UserBean">
        SELECT * FROM user WHERE name = #{name} AND password = #{password}
    </select>

</mapper>

application.yml

spring:
  datasource:
    name: xin1
    url: jdbc:mysql://localhost:3305/xin1
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
#Using jdbc to connect database


mybatis:
  mapper-locations: classpath:mapper/UserMapper.xml
  type-aliases-package: com.huang.xin01.bean
#Specify the xml file to be scanned by mybatis

5. Writing of userservice interface and UserServiceImpl class
UserService

package com.huang.xin01.service;

import com.huang.xin01.bean.UserBean;
import org.springframework.stereotype.Repository;

/*
The service layer interface is implemented by serviceImpl class
 */
//@Repository
public interface UserService {
    UserBean loginIn(String name,String password);
}

UserServiceImpl

package com.huang.xin01.service.serviceImpl;

import com.huang.xin01.bean.UserBean;
import com.huang.xin01.mapper.UserMapper;
import com.huang.xin01.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/*
Service layer, calling Dao layer to realize login function
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public UserBean loginIn(String name, String password) {
        return userMapper.getInfo(name, password);
    }
}

6. Modify the startup class Xin01Application class (add the annotation @ mapperscan(“ com.huang.xin01.mapper”))
Xin01Application

package com.huang.xin01;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/*
The startup program of the project must be added with @ MapperScan annotation to scan mapper configuration file
 */
@SpringBootApplication
@MapperScan("com.huang.xin01.mapper")
public class Xin01Application {

    public static void main(String[] args) {

        SpringApplication.run(Xin01Application.class, args);
    }

}

7. Write the test class Xin01ApplicationTests (in the test package)
Xin01ApplicationTests

package com.huang.xin01;

import com.huang.xin01.bean.UserBean;
import com.huang.xin01.service.UserService;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/*
Test class, found that the dependent exclusions conflict with RunWith, commented
 */
@RunWith(SpringRunner.class)
@SpringBootTest
class Xin01ApplicationTests {

    @Autowired
    UserService userService;
    @Test
    void contextLoads() {
        UserBean userBean = userService.loginIn("huang","huang");
        System.out.println("This user id by"+userBean.getId());

    }

}

(5) Project testing

Note: some versions will report red for @ Autowired annotation. You can select settings

It is recommended to change this change to the default setting.
1.test test
Run the Test method and observe the output result of the console, which is correct as follows:

2. Project test
Run the startup program and enter localhost:8080/login The effect is as follows:

Login successful

summary

Due to the different versions of each person's configurations, there may be some small problems. Welcome to put these problems in the comment area, and the blogger will answer them as soon as possible.

Keywords: Database Spring Mybatis MySQL

Added by ecco on Sun, 28 Jun 2020 08:52:33 +0300