SpringBoot integrates SSM framework and Ajax

1. Introduction to SpringBoot

SpringBoot is a collection that integrates Spring, SpringMVC and related common frameworks by default, and completes the regular configuration by default. Regarding configuration, SpringBoot's philosophy is "Convention is greater than configuration". In the process of use, you don't need to configure it, but also comply with the configuration values ​​completed by SpringBoot.

2. Create SpringBoot project

Open https://start.spring.io, fill in the parameters for creating the project on the page, if necessary, check the dependencies that need to be added, and click the Generate button to download the project.

Unzip the downloaded project archive to get the project folder, which should be moved to Workspace. In Eclipse, import the project through Import> Existing Maven Projects.

When importing, make sure that the current computer can connect to the Maven server! This project needs to download a large number of dependent jar packages from the Maven server!

If the project does not start to update automatically, you can right-click the project, select Maven> Update Project, and check Force update... in the pop-up dialog box and try to update. If it still fails to update, you can try to lower the version of springboot that you depend on.

It is recommended to use Eclipse Oxygen (4.7) and above. If you are using a lower version of Eclipse, the Maven version error may be prompted in the pom.xml file! You can ignore this error and it will not affect the operation of the project!

3. SpringBoot project structure

For example, the created project structure:

[Java Resources]
	[src/main/java]
		[cn.tedu.springboot]
			ServletInitializer.java
			SpringbootApplication.java
	[src/main/resources]
		[static]
		[templates]
		application.properties
	[src/test/java]
		[cn.tedu.springboot]
			SpringbootApplicationTests.java

Note: The above cn.tedu.springboot package is determined according to the Group and Artifact set when the project is created, and it is also the root package of the component scan set in the current project! Therefore, during subsequent programming, all component classes (such as controller classes) must be placed in this package or its sub-packages!

Note: The name of the SpringbootApplication class is also determined by the Artifact set when the project is created. This class is the startup class of the SpringBoot project. When it needs to run, execute the main() method in this class!

Note: The SpringBoot project has built-in Tomcat. When the startup class is run, the project will be deployed to the built-in Tomcat!

Note: The static folder under src/main/resources is used to store static resources, such as storing .html, .css, .js and pictures!

Note: The templates folder under src/main/resources is used to store template pages. For example, when using Thymeleaf, you should put relevant template pages here!

Note: The application.properties file under src/main/resources is the only configuration file of the SpringBoot project, and all custom configurations should be configured in this file! There are also some SpringBoot projects that use the configuration file application.yml. The difference from application.properties is only the syntax of configuration, and the function and positioning are exactly the same!

Note: There is the cn.tedu.springboot package under src/test/java. This package name is also determined when the project is created. All unit test classes in the SpringBoot project must be placed in this package or sub-package! Otherwise, the Spring environment will not be loaded when performing unit tests! In the SpringbootApplicationTests test class, the two annotations before the declaration statement of the class are also the annotations that must be added to each unit test class!

4. Add a static web page to the SpringBoot project

Create index.html under src/main/resources/static. The content can be designed by yourself. After completion, start the project (execute the main() method in the SpringbootApplication class), open the browser, and go through http://localhost:8080/ Can visit this page!

Because index.html is the file name of the default welcome page, it is not necessary to explicitly use http://localhost:8080/index.html in the URL when visiting.

5. Modify the port number of the built-in Tomcat in the SpringBoot project

Add configuration in application.properties under src/main/resources:

server.port=8888

The default port number of the HTTP protocol is 80. You can also modify the port number to this value. If you are using the Linux operating system, you need to set related permissions to use port 80.

6. Process the request in the SpringBoot project

Create a subpackage controller under the project's root package cn.tedu.springboot, and create the controller class HelloController in this subpackage, and add the @RestController annotation before the class:

package cn.tedu.springboot.controller;

import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

}

@RestController is equivalent to @Controller + @ResponseBody , that is: after adding this annotation, the current class is the controller class, and all the methods of processing the request in the current class are the response body, which is equivalent to adding before each method of processing the request @ResponseBody! @RestController is not an annotation unique to the SpringBoot project. It can also be used in ordinary SpringMVC projects, but it needs to be configured separately!

Note: The SpringBoot project has configured SpringMVC's DispatcherServlet by default, and the mapped path is / . Therefore, when developing with SpringBoot, the design request path does not need to use .do as a suffix! *

Then, add processing request in the controller class:

@GetMapping("hello")
public String showHello() {
	return "Hello, <b>SpringBoot</b>!!!";
}

The above @GetMapping is equivalent to @RequestMapping(method=RequestMethod.GET), that is, the restriction request method must be a GET type request! In addition, there is @PostMapping......

  1. Use SpringBoot to develop user registration function

7.1. Develop front-end pages

The normal development process should be the last page!

Create a user registration page under src/main/resources/static.

7.2. Use the controller to receive and process requests

In order to facilitate receiving the registration data submitted by users, first, an entity class of cn.tedu.springboot.entity.User user data should be created:

Create the cn.tedu.springboot.controller.UserController controller class and add @RestController and @RequestMapping("user") before the controller class:

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

}

Then, add methods to receive and process the request:

@PostMapping("reg")
public void reg(User user) {
	// 目前无法确定注册成功与否,暂时使用void作为返回值类型
	
	System.err.println("UserController.reg()");
	System.err.println("\t" + user);
	
	// TODO 将用户数据写入到数据库中
}

On the front-end page, make sure that the registration request is submitted to /user/reg. If it is correct, start the project and observe whether the user's registration data can be submitted to the server-side controller!

7.3. Database connection

The SpringBoot project does not have the dependencies required for integrated database programming by default! You can add it when you create the project, or you can add related dependencies in pom.xml after the project is successfully created!

The dependencies on MyBatis and MySQL are:

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

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

Note: If you add database-related dependencies to the SpringBoot project, but do not configure database connection-related information, an error will be reported when you start the project, because SpringBoot will load the database-related information when it starts!

Then, you need to add 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=root

When configuring the database connection, you do not need to configure the driverClassName, and SpringBoot will automatically find it from the jar package of the database connection!

After adding the above configuration, even if the configuration value is wrong, it will not affect the project startup! However, you should check whether the configuration is correct in time! You can try to get the database connection through the unit test. If you can connect, the configuration is correct. If you cannot connect, the configuration is wrong, or the related jar package is damaged!

Write and execute unit tests in SpringbootApplicationTests:

@Autowired
private DataSource dataSource;

@Test
public void getConnection() throws SQLException {
	Connection conn = dataSource.getConnection();
	System.err.println(conn);
}

Because the SpringBoot unit test will load the configuration and Spring environment of the entire project before execution, the objects that can be obtained through getBean() in the traditional SpringMVC project can be automatically assembled in the SpringBoot project!

7.4. Insert data through MyBatis

Create the cn.tedu.springboot.mapper.UserMapper interface and add abstract methods to the interface:

Integer insert(User user);

Then, you need to configure the location of the interface file! You can add the @Mapper annotation directly before the declaration statement of the interface! When using this approach, each MyBatis interface needs to add this annotation! There is another way to add @MapperScan annotations for configuration before starting the class:

@SpringBootApplication
@MapperScan("cn.tedu.springboot.mapper")
public class SpringbootApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootApplication.class, args);
	}

}

Create a folder named mappers under src/main/resources, which is specially used to store XML files for configuring SQL statements, and copy and paste the UserMapper.xml file under this folder to configure:

<mapper namespace="cn.tedu.springboot.mapper.UserMapper">

	<insert id="insert"
		useGeneratedKeys="true"
		keyProperty="id">
		INSERT INTO t_user (
			username, password,
			age, phone,
			email, is_delete,
			department_id
		) VALUES (
			#{username}, #{password},
			#{age}, #{phone},
			#{email}, #{isDelete},
			#{departmentId}
		)
	</insert>
	
</mapper>

In the SpringBoot project, you still need to configure the location of the XML file, you need to add configuration in application.properties:

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

After completion, write and execute unit tests:

@Autowired
private UserMapper userMapper;

@Test
public void insert() {
	User user = new User();
	user.setUsername("boot");
	user.setPassword("1234");
	Integer rows = userMapper.insert(user);
	System.err.println("rows=" + rows);
}

In order to ensure the "unique user name", you can check whether the user name has been registered before the user attempts to register, then "query user data based on the user name", determine whether the query result is null, you can judge the answer!

So, add in the UserMapper.java interface:

User findByUsername(String username);

And configure SQL mapping in UserMapper.xml:

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

After completion, you should still write and execute unit tests:

@Test
public void findByUsername() {
	String username = "root";
	User user = userMapper.findByUsername(username);
	System.err.println(user);
}

Then, apply the above method to the process of processing the request of the controller:

@PostMapping("reg")
public JsonResult reg(User user) {
	System.err.println("UserController.reg()");
	System.err.println("\t" + user);
	
	JsonResult jsonResult = new JsonResult();
	
	// 检查该用户名是否已经被注册
	String username = user.getUsername();
	User result = userMapper.findByUsername(username);
	// 判断查询结果是否为null
	if (result == null) {
		// 将用户数据写入到数据库中
		userMapper.insert(user);
		jsonResult.setState(1);
	} else {
		// 用户名已经被注册
		jsonResult.setState(2);
		jsonResult.setMessage("您尝试注册的用户名(" + username + ")已经被占用!");
	}
	
	return jsonResult;
}

Guess you like

Origin blog.csdn.net/qq_37669050/article/details/102508588