Using IDEA to build a simple SpringBoot project

1.File->new->project;

2. select "Spring Initializr" and click next; (jdk1.8 is OK by default)

3. improve the project information, the group name can be modified, and the project name can be modified; The final project name is: test. The package name under src->main->java will be: com->example->test; Click next;

4. Check Spring Web Starter under the Web (most SpringBoot projects created on the Internet check the Web option, but higher versions of SpringBoot do not have this option. Just check Spring Web Starter, and 2.1.8 is Spring Web); Template Engines check Thymeleaf; SQL check: MySQL Driver, JDBC API and MyBatis Framework; Click next;

5. select the project path and click finish; Open a new window;

6. newly created project directory structure

7. click Maven on the right and click settings (wrench icon) to configure the Maven warehouse of the project;

8. (1) select the local Maven path; (2) Check the option at the back of the configuration file, and then modify it to the local Maven configuration file, which will directly find the local warehouse location according to the configuration file;

9. after configuration, if there is no automatic package import, you can click the re import package button in the upper left corner or the download button to select to download all source files and documents;

10. create a new index HTML page, as the initial page for startup;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>hello</title>
</head>
<body>
    Hello! Beginner, I am SpringBoot Simple launch page for!
</body>
</html>

11. on com Example Create a new Controller folder under test, and create a simple helloController class under the Controller folder; (the @Controller annotation should be added to the Controller class. When the project is started, SpringBoot will automatically scan and load the Controller.)

package com.example.test.controller;
 
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class HelloController {
 
    @RequestMapping("/index")
    public String sayHello(){
        return "index";
    }
}

12. configure the basic information of DataSource in the application under the resources folder. The application file has two file formats. One is in properties is the suffix. One is based on yml is a suffix, and the two configurations are slightly different. For details, please refer to this website: https://blog.csdn.net/qq_29648651/article/details/78503853 ; I use it here The file format of the yml suffix. Right click the application file, select Refactor, select Rename, and change the suffix to yml;

 

spring:
  datasource:
    name: test  #Database name
    url: jdbc:mysql://localhost:3306/test #url
    username: root  #user name
    password: 123456  #password
    driver-class-name: com.mysql.jdbc.Driver  #Database link driver

13. run the project startup class testapplication Java;

It can be found that there is a WARN warning on the above, because the relevant files for writing MyBatis have not been configured, which will be explained in detail below;

2019-08-02 09:14:27.473  WARN 9120 --- [           main] o.m.s.mapper.ClassPathMapperScanner      : No MyBatis mapper was found in '[com.example.test]' package. Please check your configuration.

14. enter localhost:8080 in the browser, and press enter to display the initial index interface; Now that the preliminary construction of the project has been completed, some simple business logic can be done, such as simple functions such as obtaining information from the database and logging in;

15. in the next step, let's link to the Database first; Click the Database on the right and click the "plus" sign to create a new Database link;

16. fill in relevant database information and click Test Connection;

17. if the link fails, it may be the drive problem. Click the small wrench in the upper left corner to enter the database setting interface;

18. after the connection is successful, the database information and the basic information of the user table are displayed. Let's follow this example;

19. The springboot project is roughly divided into four layers:

(1) Bean layer: also known as model layer, model layer, entity layer and entity layer, which are mapped entity classes of database tables and store POJO objects;

(2) Dao layer: including xxxmapper Java (database access interface class), xxxmapper XML (database link implementation); (some people like to use Dao for naming, while others like Mapper for naming. I'm used to it.)

(3) Service layer: also called service layer, business layer, including xxxservice Java (business interface class), xxxserviceimpl Java (business implementation class); (you can create an impl file in the service folder to put the business implementation class, or put the business implementation class in a separate folder to make it clearer)

(4) Web layer: it is the Controller layer, which realizes the interaction with the web front end.

According to the above four layers, create the directory structure as follows:

20. code display:

(1) Add the MyBatis configuration in the application configuration file:

spring:
  datasource:
    name: test  #Database name
    url: jdbc:mysql://localhost:3306/test #url
    username: root  #user name
    password: 123456  #password
    driver-class-name: com.mysql.jdbc.Driver  #Database link driver
 
mybatis:
  mapper-locations: classpath:mapper/*.xml  #Configuration mapping file
  type-aliases-package: com.example.test.bean #Configure entity classes

(2) Pom XML file configuration information

<?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 http://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.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>test</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>
        <!--thymeleaf Template engine configuration-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--Web rely on-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--MyBatis allocation-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <!--MySQL Database configuration-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
            <scope>runtime</scope>
        </dependency>
        <!--Unit test configuration-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
</project>

(3)Bean entity class generates set and get methods according to the database table;

package com.example.test.bean;
 
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;
    }
}

(4) DAO layer access database interface file:

package com.example.test.mapper;
 
import com.example.test.bean.UserBean;
 
public interface UserMapper {
 
    UserBean getInfo(String name, String password);
 
}

(5) The DAO layer accesses the database implementation file. Note that the namespace attribute of the <mapper> tag should fill in the path to the database interface class file:

<?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" >
<mapper namespace="com.example.test.mapper.UserMapper">
 
    <select id="getInfo" parameterType="String" resultType="com.example.test.bean.UserBean">
        SELECT * FROM user WHERE name = #{name} AND password = #{password}
    </select>
 
</mapper>

(6) Service layer business interface class preparation:

package com.example.test.service;
 
import com.example.test.bean.UserBean;
 
public interface UserService {
 
    UserBean loginIn(String name, String password);
 
}

(7) When writing the Service layer business implementation class, note that @Service should be annotated and DAO injected:

package com.example.test.serviceImpl;
 
import com.example.test.bean.UserBean;
import com.example.test.mapper.UserMapper;
import com.example.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
@Service
public class UserServiceImpl implements UserService {
 
    //Inject DAO into Service layer
    @Autowired
    private UserMapper userMapper;
 
    @Override
    public UserBean loginIn(String name, String password) {
        return userMapper.getInfo(name, password);
    }
}

(8) The project startup class needs to add annotation @MapperScan scan the mapper interface when the project is started, otherwise an error will be reported that the mapper file cannot be found:

package com.example.test;
 
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
@MapperScan("com.example.test.mapper")
public class TestApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
 
}

(9) write a test class to see if it can successfully access the database and obtain database information:

package com.example.test;
 
import com.example.test.bean.UserBean;
import com.example.test.service.UserService;
import org.junit.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;
 
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestApplicationTests {
 
    @Autowired
    UserService userService;
 
    @Test
    public void contextLoads() {
        UserBean userBean = userService.loginIn("a", "a");
        System.out.println("This user ID Is:");
        System.out.println(userBean.getId());
    }
 
}

(10) In the controller layer, add the @controller annotation and inject the Service service:

package com.example.test.controller;
 
import com.example.test.bean.UserBean;
import com.example.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
@Controller
public class LoginController {
 
    //Inject Service into Web tier
    @Autowired
    UserService userService;
 
    @RequestMapping("/login")
    public String show(){
        return "login";
    }
 
    @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";
        }
    }
 
}

(11) html file:

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login</title>
</head>
<body>
    <form role="form" action = "/loginIn" method="post">
        Account No.:<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

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

error.html

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

21. run the test class first to see if the database information is successfully obtained:

22. at the same time, a warning message was found that the jar package of the database connection was faulty:

2019-08-02 11:25:04.150  WARN 16868 --- [           main] com.zaxxer.hikari.util.DriverDataSource  : Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.

Open pom XML file. It is found that the version number of the jar package for which the database connection is not specified in the configuration file. It is imported with the version tag

<version>5.1.41</version>

Rerun the test class and eliminate the warning

23. run testapplication Java file. Start the project without any warning information. Enter the browser and enter localhost:8080/login

This is the perfect end of the project.

 

The project source code is placed on GitHub, which can be downloaded for reference: https://github.com/redesperado/SpringBoot.git

There is an item to add, delete, modify and query functions based on this item, which is for reference only: https://github.com/redesperado/test1.git

 

If you encounter any problems during the creation process, you can see them in the links provided below. These are the problems I encountered during the creation of the project. I hope they can help you:

(1) Error starting: error starting applicationcontext To display the conditions report re run your application with'debug'enabled

https://blog.csdn.net/baidu_39298625/article/details/98261102

(2) Mapper XML file database field red

https://blog.csdn.net/baidu_39298625/article/details/98265845

(3) The project starts normally. When accessing the default index page 404

https://blog.csdn.net/baidu_39298625/article/details/98501840

(4) Error when linking MySQL database: java Sql Sqlexception: the server time zone value ' й Internal ׼ʱ 'is unrecognized or representatives more than one time zone You must configure either the server or jdbc driver (via the servertimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support

https://blog.csdn.net/baidu_39298625/article/details/100915264

(5) Login of Chinese user name failed without error message

https://blog.csdn.net/baidu_39298625/article/details/103494461

Tags: Java

Posted by jaikar on Thu, 02 Jun 2022 00:14:20 +0530