1. SpringBoot framework

The SpringBoot framework can be simply understood as “an enhanced Version of the SpringMVC framework, which greatly simplifies configuration and integrates most common dependencies by default”.

2. How to create a SpringBoot project

There are three main ways to create SpringBoot:

  • Create child projects based on SpringBoot’s parent project;
  • If you use Eclipse, you need to install the Spring Tools Suite plug-in. If you use Intellijia IDEA, you do not need to install any plug-in.
  • throughhttps://start.spring.ioThe web site creates the project, and then imports the project into the development tool.

3. Create a SpringBoot project

Go to https://start.spring.io and confirm the following parameters:

  • [Project] : Maven Project
  • [Language] : Java
  • [SpringBoot] : 2.1.14
  • [Group] : cn. Tedu
  • Artifact: Sample
  • [Name] : sample
  • [Package Name] : cn.tedu.sample
  • 【Packaging】 : War
  • [Java] : 8
  • 【Dependencies】 : None

After you are sure, click the Generate button in the page, the automatic download will start, and you will get the sample.zip package.

Decompress sample.zip to obtain the sample folder. This folder is the created SpringBoot project.

Maven Projects: Import > Existing Maven Projects: Import > Existing Maven Projects: Import > Existing Maven Projects: Import > Existing Maven Projects: Import > Existing Maven Projects: Import > Existing Maven Projects You can connect to the Maven server without any problems. If automatic downloads are not started, you can right click on the Project and choose Maven > Update Project to Update the Project, or even force the Project to Update.

Note: Depending on the plug-in installed by the development tool, there may be some additional branches or ICONS in the project structure that do not affect normal development and operation.

Note: If you are using a lower version of Eclipse, you may have built in a lower version of Maven environment. After creating a SpringBoot project, the pom.xml file may report an error, but it can be ignored and does not affect development and operation.

4. Start the SpringBoot project

In generated projects, by default, there is the cn.tedu.sample package under SRC /main/ Java. The name of this package is determined by the Group and Artifact filled in when the project is created, and this is the package that the current SpringBoot project is configured to scan for components by default, so, Subsequent self-created component classes must be placed in this package or its descendants!

The default package name cannot be changed, and it is recommended that all classes be placed in this package or its descendants.

Under the cn.tedu.sample package, there is the SampleApplication class by default. This class is named based on the Artifact that was filled in when the project was created, and this class has the main() method that will launch the entire project! Therefore, SampleApplication is also called the start class of the current project!

SpringBoot projects come with built-in Tomcat. When you start a project, the project is compiled, packaged, and deployed to the built-in Tomcat, and then Tomcat is started!

Since the built-in Tomcat also occupies port 8080 by default, you must stop Tomcat before starting the project, and do not start the project repeatedly!

The SRC /test/ Java package also contains the SampleApplicationTests class with contextLoads(), which has no code in its body. Executing the method through a unit test should pass the test.

When unit tests are performed in SpringBoot, all environments of the project are loaded (reading configurations, loading Spring containers, etc.), all unit test classes must be placed in the cn.tedu.sample package or its descendants, and, The declaration of the test class must be preceded by the same annotations as the SampleApplicationTests class!

With SpringBoot 2.1.x series, you need to add two annotations before the unit test class. With SpringBoot 2.2.x series, you need to add only one annotation! Regardless of which version you use, configure the annotations by referring to the unit test class that exists by default!

5. Add static resources to the project

Static resources: web page files (.html files), image files,.CSS files,.js files, on the server, can be directly requested by the client files.

In the SpringBoot project, under SRC /main/resources, there is a static folder by default, which is used to store static resources!

In fact, static resources can also be placed in the webApp folder of your project. SpringBoot recommends that static resources be placed under Static.

The index. HTML file can be created static, and the contents of the file can be arbitrarily designed.

Then, start the project, open a browser, type in the url http://localhost:8080 to see your own design of the web page.

The following log appears in the console when the project is started:

Tomcat started on port(s): 8080 (http) with context path ''
Copy the code

As you can see, internal Tomcat sets the context path value to an empty string when deploying the current project, so there is no need to add the project name to the URL accessing the project!

Since this attempt to access the resource is index.html, is the default resource name, so, there is no need to explicitly add the resource name in the URL!

In a SpringBoot project, under SRC /main/resources, there is an application. Properties file by default, which is the configuration file for the project.

You can modify the ports used by Tomcat in the configuration file. You need to add the following configuration:

server.port=80
Copy the code

Because port 80 is the default HTTP port, when changed to port 80, restart the project (stop first, then start), in the browser through http://localhost to access the previous web page!

Note: If you use Linux or Unix derived operating systems such as Mac OS, these operating systems strictly manage the port number. By default, you cannot change the port number to 80 unless you set the port number to 80 in the operating system.

6. Use the controller to receive requests from clients

SRC /main/ Java cn.tedu.sample create a sub-controller package and create HelloController class in this sub-package to design the request and handle:

package cn.tedu.sample.controller;

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

@Controller
public class HelloController {
	
	@RequestMapping("hello")
    @ResponseBody
	public String hello(a) {
		return "SpringBoot is so good!!"; }}Copy the code

Restart the project, and you can access the method of the above controller through http://localhost/hello in the browser.

In the SpringBoot project, the default path of DispatcherServlet mapping is set to /*, that is, all resources (of course, static and webApp folders have been set to static resource folder, so direct access is allowed), so, When you configure the request path using the @requestMapping annotation, you do not need to use.do or other suffixes, although you can add suffixes as long as the access is consistent.

In the SpringBoot project, all available encoding has been set to UTF-8, so the SpringBoot project is fully supported by Chinese by default!

When you determine that the response on the server side is “ResponseBody”, the @controller annotation added before the Controller class can be replaced with @restcontroller. This annotation is equivalent to @controller + @responsebody. When a class declaration is preceded by @RestController, each method in the class does not need to add @responseBody to “respond body.”

7. Connect to the database

By default, the SpringBoot project does not have jar packages that integrate the database and database programming framework. You need to check the relevant dependencies when creating the project, or add the relevant code to the pop.xml after creating the project:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.2</version>
</dependency>

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

For example, mysql-connector-java does not specify a version number. For example, mysql-connector-java does not specify a version number. Of course, if you must use a particular version, you can add your own

node for configuration, and use the specified version!

Once the above dependencies are added, when the project is started, the configuration information for connecting to the database will be automatically loaded. If it is not configured, the startup will fail! Therefore, you must add a configuration in application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/tedu_ums? useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai spring.datasource.username=root spring.datasource.password=rootCopy the code

When you add the above configuration, SpringBoot will not fail to start again, even if the above configuration information is incorrect! Because the project will only “load information”, not “direct database”, so, above configuration, as long as the basic format is correct!

You can write unit tests under SRC /test/ Java to try to connect to the database to check that the above configuration information is correct! Add the following code to the SampleApplicationTests class in the cn.tedu.sample package:

@Autowired
public DataSource dataSource;

@Test
public void getConnection(a) throws SQLException {
    Connection conn = dataSource.getConnection();
    System.err.println(conn); // Err is only used to output red logs for easy observation.
}
Copy the code

When programming with the SpringBoot framework, any object that can be obtained with getBean() in traditional SSM frameworks can be assembled by adding auto-assembly annotations!

8. Realize database programming with MyBatis

[Target] Insert user data into the user data table.

Create entity subpackage in cn.tedu.sample to store entity classes and create User class in this package:

public class User {
    private Integer id;
    private String username;
    private String password;
    private Integer age;
    private String phone;
    private String email;
}
Copy the code

Create a UserMapper interface in this package and add abstract methods to the interface:

Integer addnew(User user);
Copy the code

Then, you need to add the @mapperscan annotation to specify the location of the interface before starting the declaration of the SampleApplication class!

Create the mappers folder under SRC /main/resources to hold the XML file where the SQL statement is configured. In this folder, paste the usermapper. XML and configure the SQL statement mapping for the above abstract method:


      
<! DOCTYPEmapper
  PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  
<mapper namespace="cn.tedu.sample.mapper.UserMapper">

	<insert id="addnew">
		INSERT INTO t_user (
			username, password, age, phone, email
		) VALUES (
			#{username}, #{password}, #{age}, #{phone}, #{email}
		)
	</insert>

</mapper>
Copy the code

Then, you also need to add configuration in application.properties to specify the location of the XML file:

mybatis.mapper-locations=classpath:mappers/*.xml
Copy the code

The UserMapperTests class can be created under the SRC /test/ Java cn.tedu.sample package. The UserMapperTests class can be created under this package. Add a comment referring to the original SampleApplicationTests class:

package cn.tedu.sample.mapper;

import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTests {}Copy the code

Then, write and execute the unit test method in the test class:

package cn.tedu.sample.mapper;

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;

import cn.tedu.sample.entity.User;

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTests {
	
	@Autowired
	public UserMapper userMapper;
	
	@Test
	public void addnew(a) {
		User user = new User();
		user.setUsername("SpringBoot");
		user.setPassword("1234");
		user.setAge(28);
		user.setPhone("13900139008");
		user.setEmail("[email protected]");
		Integer rows = userMapper.addnew(user);
		System.err.println("rows="+ rows); }}Copy the code

[Target] Query user data based on the user name

SQL statements that need to be executed are as follows:

select * from t_user where username=?
Copy the code

Add an abstract method to the UserMapper interface:

User findByUsername(String username);
Copy the code

And configure the mapping in usermapper.xml:

<select id="findByUsername" resultType="cn.tedu.sample.entity.User">
	SELECT * FROM t_user WHERE username=#{username}
</select>
Copy the code

When complete, write and execute unit tests in UserMapperTests:

@Test
public void findByUsername(a) {
    String username = "test";
    User user = userMapper.findByUsername(username);
    System.err.println(user);
}
Copy the code

9. Complete the user registration function

When the user tries to register, the user will fill in the registration information in the page, and then click the button to submit the request! The request will be received by the controller on the server side, but the controller is not responsible for adding, deleting, modifying, and checking the data, so it will be handed over to UserMapper for execution!

Next, we need to develop the functionality of the controller by creating the util sub-package under cn.tedu.sample and creating the usual JSON result type in this package:

public class JsonResult<T> {
    private Integer state;
    private String message;
    private T data;
}
Copy the code

In cn. Tedu. Sample. The controller package created in UserController controller class, before the declaration of a class to add @ RestController and @ RequestMapping annotations (” user “), and declare the persistence layer objects:

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserMapper userMapper;
}
Copy the code

Then, add a method to the class to handle the “register” request:

// http://localhost/user/reg? username=jsd2020&password=5678&age=19&phone=13700137777&[email protected]
@RequestMapping("reg")
public JsonResult<Void> reg(User user) {
    // Prepare the return value object
    JsonResult<Void> jsonResult = new JsonResult<Void>();
    // Query the database based on username in the user parameter
    User result = userMapper.findByUsername(user.getUsername());
    // Check whether the query result is null
    if (result == null) {
        // If no matching data is found, the user name is not occupied and registration is allowed
        userMapper.addnew(user);
        jsonResult.setState(1);
    } else {
        // No: If matching data is found, the user name has been occupied and registration is not allowed
        jsonResult.setState(2);
        jsonResult.setMessage("Registration failed! The user name you tried to register is already in use!");
    }
    / / return
    return jsonResult;
}
Copy the code

When you’re done, restart the project and open your browser to test by typing in the url.

Create an asynchronous request to the server using Ajax, and process the result:

Copy the code