preface


Spring MVC is a native framework built on top of the Servlet API and has been included in the Spring framework since the beginning. This paper mainly introduces the architecture and analysis of Spring MVC, and uses Spring Boot + Spring MVC + MyBatis (SSM) + Thymeleaf (template engine) framework to build a simple and fast Web project.

Web MVC architecture and analysis


MVC three-tier architecture is shown in the figure, and the red font represents the core module. Where, each layer of MVC is:

  • **Model (Model layer) ** handles the core business (data) logic, and the Model objects are responsible for accessing data in the database. The “data” here is not limited to the data itself, but also the logic that processes the data.
  • **View (View layer) ** is used to display data, which is usually created from model data.
  • **Controller (Controller layer) ** Is used to process user input requests and respond to output from trying to read data, control user input, and send data to the model. The Controller is the intermediary between the Model and View for two-way data transfer.

Spring MVC architecture and analysis


Spring MVC processes the flow of an HTTP request, as shown below:

Spring Boot + Spring MVC + MyBatis + Thymeleaf


In this section we will implement a paging query by building the project.

1. Project construction

The project structure is shown in the figure below:

1.1 POM introduces related dependencies
<?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.1.9. RELEASE</version>
		<relativePath/> <! -- lookup parent from repository -->
	</parent>
	<groupId>cn.zwqh</groupId>
	<artifactId>spring-boot-ssm-thymeleaf</artifactId>
	<version>0.0.1 - the SNAPSHOT</version>
	<name>spring-boot-ssm-thymeleaf</name>
	<description>spring-boot-ssm-thymeleaf</description>

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

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>


		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>

		<! -- Hot Deployment Module -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional> <! -- This requires hot deployment to be true -->
		</dependency>


		<! Mysql database driver -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

		<! -- mybaits -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.0</version>
		</dependency>

		<! -- pagehelper -->
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper-spring-boot-starter</artifactId>
			<version>1.2.12</version>
		</dependency>
		
		<! -- thymeleaf -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

	</dependencies>

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

</project>

Copy the code
1.2 WebMvcConfig configuration
package cn.zwqh.springboot.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;


@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

	/** * Static resource configuration */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {	
		registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");// Static resource path CSS,js,img, etc
		registry.addResourceHandler("/templates/**").addResourceLocations("classpath:/templates/");/ / view
		registry.addResourceHandler("/mapper/**").addResourceLocations("classpath:/mapper/");//mapper.xml
		super.addResourceHandlers(registry);
		
	}

	/** * View controller configuration */
	@Override
	public void addViewControllers(ViewControllerRegistry registry) {	
		registry.addViewController("/").setViewName("/index");// Set the default jump view to /index
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        super.addViewControllers(registry);
		
		
	}
	/** * View parser configuration control Controller String Returns page view jump control */
	@Override
	public void configureViewResolvers(ViewResolverRegistry registry) {
	   // registry.viewResolver(new InternalResourceViewResolver("/jsp/", ".jsp"));
	    super.configureViewResolvers(registry); }}Copy the code
1.3 application. The properties configuration
#thymeleaf
spring.thymeleaf.cache=false
#datasourceSpring. The datasource. The driver - class - name = com. Mysql. Cj. JDBC. Driver spring. The datasource. Url = JDBC: mysql: / / 127.0.0.1:3306 / db_test? useUnicode=true&characterEncoding=UTF-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
#mybatis
mybatis.mapper-locations=classpath:/mapper/*.xml
#logging
logging.path=/user/local/log
logging.level.cn.zwqh=debug
logging.level.org.springframework.web=info
logging.level.org.mybatis=error

Copy the code
1.4 the Controller
@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;

	@GetMapping("/list")
	public ModelAndView showUserList(int pageNum, int pageSize) {
		PageInfo<UserEntity> pageInfo = userService.getUserList(pageNum, pageSize);
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("index");
        modelAndView.addObject("pageInfo",pageInfo);
		returnmodelAndView; }}Copy the code
1.5 the Service and ServiceImpl

UserService

public interface UserService {

	PageInfo<UserEntity> getUserList(int pageNum, int pageSize);

}

Copy the code

UserServiceImpl

@Service
public class UserServiceImpl implements UserService{

	@Autowired
	private UserDao userDao;

	@Override
	public PageInfo<UserEntity> getUserList(int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		List<UserEntity> list=userDao.getAll();
		PageInfo<UserEntity> pageData= new PageInfo<UserEntity>(list);
		System.out.println("Current page:"+pageData.getPageNum());
		System.out.println("Page size:"+pageData.getPageSize());
		System.out.println("Total:"+pageData.getTotal());	
		System.out.println("Total pages:"+pageData.getPages());	
		returnpageData; }}Copy the code
1.6 the Dao
public interface UserDao {
	/** * Get all users *@return* /
	List<UserEntity> getAll(a);
	
}
Copy the code

Remember to add ** @mapperscan ** to the startup class

@SpringBootApplication
@MapperScan("cn.zwqh.springboot.dao")
public class SpringBootSsmThymeleafApplication {

	public static void main(String[] args) { SpringApplication.run(SpringBootSsmThymeleafApplication.class, args); }}Copy the code
1.7 Mapper XML
<?xml version="1.0" encoding="UTF-8"? >

      
<mapper namespace="cn.zwqh.springboot.dao.UserDao">
	<resultMap type="cn.zwqh.springboot.model.UserEntity" id="user">
		<id property="id" column="id"/>
		<result property="userName" column="user_name"/>
		<result property="userSex" column="user_sex"/>
	</resultMap>
	<! Get all users -->
	<select id="getAll" resultMap="user">
		select * from t_user
	</select>
</mapper>


Copy the code
1.8 entity UserEntity
public class UserEntity {

	private Long id;
	private String userName;
	private String userSex;
	public Long getId(a) {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getUserName(a) {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserSex(a) {
		return userSex;
	}
	public void setUserSex(String userSex) {
		this.userSex = userSex; }}Copy the code
1.9 HTML page

      
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>Thymeleaf is a modern server-side Java templating engine for Web and standalone environments. SpringBoot recommends Thymeleaf.</p>
<p>Here is an example of a table:</p>
<table border="1">
	<thead>
		<tr>
			<th width="100">ID</th>
			<th width="100">The name</th>
			<th width="100">gender</th>
		</tr>
	</thead>
	<tbody>
		<tr th:each="user:${pageInfo.list}">
			<td th:text="${user.id}"></td>
			<td th:text="${user.userName}"></td>
			<td th:text="${user.userSex}"></td>
		</tr>
	</tbody>
</table>
<p>
<a th:href="${'/user/list? pageNum='+(pageInfo.pageNum-1>=1? pageInfo.pageNum-1:1)+'&pageSize=10'}">The previous page</a>
    
<a th:href="${'/user/list? pageNum='+(pageInfo.pageNum+1<=pageInfo.pages? pageInfo.pageNum+1:pageInfo.pages)+'&pageSize=10'}">The next page</a>The total number of:<span th:text="${pageInfo.total}"></span>
</p>
</body>
</html>
Copy the code

test

Through the browser visit: http://127.0.0.1:8080/user/list? PageNum =1&pageSize=10 Perform the test. The effect is as follows:

The sample code

github

Yards cloud

The copyright of this article belongs to Chaowu And Qinghan, please indicate the source.

Spring Boot 2.X(3) : Using Spring MVC + MyBatis + Thymeleaf to develop Web applications

The original address: https://www.zwqh.top/article/info/2

If the article is helpful to you, please scan the code to pay attention to my public number, the article continues to update…