Preface
Spring MVC is a native framework built on the Servlet API and included in the Spring framework from the beginning. This paper mainly describes the architecture and analysis of Spring MVC, and uses Spring Boot + Spring MVC + MyBatis (SSM) + Thymeleaf (Template Engine) framework to build a Web project simply and quickly.
Web MVC Architecture and Analysis
The MVC three-tier architecture is shown in the figure, and the red font represents the core module. The MVC layers are as follows:
- ** Model (Model Layer)** Processes core business (data) logic, and model objects are responsible for accessing data in the database. The "data" here is not only limited to the data itself, but also includes the logic to process the data.
- View (View Layer)** is used to display data, which is usually created based on model data.
- Controller ** is used to process user input requests and response outputs, from trying to read data, control user input, and send data to the model. Controller is an intermediate coordinator for bidirectional data transfer between Model and View.
Spring MVC Architecture and Analysis
Spring MVC processes an HTTP request, as shown in the figure: The whole process is described in detail: 1. The user sends the request to the front-end controller Dispatcher Servlet. 2. Dispatcher Servlet receives a request to call the processor mapper Handler Mapping. 3. Processor mapper finds the specific Controller processor according to the request URL and returns it to Dispatcher Servlet. 4. Dispatcher Servlet calls Controller to process requests through handler adapter. 5. Method of executing Controller processor. 6. The Controller execution completes and returns to ModelAndView. 7. Handler Adapter returns the Controller execution result Model AndView to Dispatcher Servlet. 8. Dispatcher Servlet passes ViewName of ModelAndView to ViewReslover, a view parser. 9.ViewReslover parses and returns a specific View view View. 10. Dispatcher Servlet passes Model data to View and renders View (i.e. fills model data into view). 11-12. Dispatcher Servlet responds to users.
Spring Boot + Spring MVC + MyBatis + Thymeleaf
In this section, we mainly build a project to achieve a paging query.
1. Project Construction
The project structure is shown as follows:
1.1 pom Introduces Relevant 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-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 needs to be true Hot Deployment Is Effective --> </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>
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 allocation */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");//Static resource paths 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); } }
1.3 application.properties configuration
#thymeleaf spring.thymeleaf.cache=false #datasource spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.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
1.4 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); return modelAndView; } }
1.5 Service and Service Impl
UserService
public interface UserService { PageInfo<UserEntity> getUserList(int pageNum, int pageSize); }
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()); return pageData; } }
1.6 Dao
public interface UserDao { /** * Get all users * @return */ List<UserEntity> getAll(); }
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); } }
1.7 Mapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.4//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <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>
1.8 Entity UserEntity
public class UserEntity { private Long id; private String userName; private String userSex; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserSex() { return userSex; } public void setUserSex(String userSex) { this.userSex = userSex; } }
1.9 html page
<!DOCTYPE html> <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 Web Modern Server Side with Independent Environment Java Template engine. SpringBoot Recommended use Thymeleaf. </p> <p>Below is an example of a table:</p> <table border="1"> <thead> <tr> <th width="100">ID</th> <th width="100">Full 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'}">Previous page</a> <a th:href="${'/user/list?pageNum='+(pageInfo.pageNum+1<=pageInfo.pages?pageInfo.pageNum+1:pageInfo.pages)+'&pageSize=10'}">next page</a> Total:<span th:text="${pageInfo.total}"></span> </p> </body> </html>
test
Access through browser: http://127.0.0.1:8080/user/list?pageNum=1&pageSize=10 Test. The effect is as follows:
Sample code
Unless otherwise specified, the copyright of this article belongs to Chao Wu Qinghan. Please indicate the source of the reprint.
Title: Spring Boot 2.X(3): Developing web Applications Using Spring MVC + MyBatis + Thymeleaf
The website of this article: https://www.zwqh.top/article/info/2