溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何使用 Spring MVC和 Thymeleaf 開發(fā) web 應用

發(fā)布時間:2021-09-10 18:15:56 來源:億速云 閱讀:145 作者:柒染 欄目:大數(shù)據

這期內容當中小編將會給大家?guī)碛嘘P如何使用 Spring MVC和 Thymeleaf 開發(fā) web 應用,文章內容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。


Spring MVC 是構建在 Servlet API 上的原生框架,并從一開始就包含在 Spring 框架中。本文主要通過簡述 Spring MVC 的架構及分析,并用 Spring Boot + Spring MVC + MyBatis (SSM)+ Thymeleaf(模板引擎) 框架來簡單快速構建一個 Web 項目。

Web MVC 架構及分析


MVC 三層架構如圖所示,紅色字體代表核心模塊。其中 MVC 各分層分別為:

  • **Model (模型層)**處理核心業(yè)務(數(shù)據)邏輯,模型對象負責在數(shù)據庫中存取數(shù)據。這里的“數(shù)據”不僅限于數(shù)據本身,還包括處理數(shù)據的邏輯。

  • **View(視圖層)**用于展示數(shù)據,通常數(shù)據依據模型數(shù)據創(chuàng)建。

  • **Controller(控制器層)**用于處理用戶輸入請求和響應輸出,從試圖讀取數(shù)據,控制用戶輸入,并向模型發(fā)送數(shù)據。Controller 是在 Model 和 View 之間雙向傳遞數(shù)據的中間協(xié)調者。 如何使用 Spring MVC和 Thymeleaf 開發(fā) web 應用

Spring MVC 架構及分析


Spring MVC 處理一個 HTTP 請求的流程,如圖所示: 如何使用 Spring MVC和 Thymeleaf 開發(fā) web 應用 整個過程詳細介紹: 1.用戶發(fā)送請求至前端控制器 DispatcherServlet。 2.DispatcherServlet 收到請求調用處理器映射器 HandlerMapping。 3.處理器映射器根據請求 URL 找到具體的 Controller 處理器返回給 DispatcherServlet。 4.DispatcherServlet 通過處理器適配器 HandlerAdapter 調用 Controller 處理請求。 5.執(zhí)行 Controller 處理器的方法。 6.Controller 執(zhí)行完成返回 ModelAndView。 7.HandlerAdapter 將 Controller 執(zhí)行結果 ModelAndView 返回給 DispatcherServlet。 8.DispatcherServlet 將 ModelAndView 的 ViewName 傳給視圖解析器 ViewReslover。 9.ViewReslover 解析后返回具體的視圖 View。 10.DispatcherServlet 傳遞 Model 數(shù)據給 View,對 View 進行渲染(即將模型數(shù)據填充至視圖中)。 11-12.DispatcherServlet 響應用戶。

Spring Boot + Spring MVC + MyBatis + Thymeleaf


本段我們主要通過構建項目,實現(xiàn)一個分頁查詢。

1.項目構建

項目結構如圖所示: 如何使用 Spring MVC和 Thymeleaf 開發(fā) web 應用

1.1 pom 引入相關依賴
<?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>

		<!-- 熱部署模塊 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional> <!-- 這個需要為 true 熱部署才有效 -->
		</dependency>


		<!-- mysql 數(shù)據庫驅動. -->
		<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 配置
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 {

	/**
	 * 靜態(tài)資源配置
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {	
		registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");//靜態(tài)資源路徑 css,js,img等
		registry.addResourceHandler("/templates/**").addResourceLocations("classpath:/templates/");//視圖
		registry.addResourceHandler("/mapper/**").addResourceLocations("classpath:/mapper/");//mapper.xml
		super.addResourceHandlers(registry);
		
	}

	/**
	 * 視圖控制器配置
	 */
	@Override
	public void addViewControllers(ViewControllerRegistry registry) {	
		registry.addViewController("/").setViewName("/index");//設置默認跳轉視圖為 /index
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        super.addViewControllers(registry);
		
		
	}
	/**
	 * 視圖解析器配置  控制controller String返回的頁面    視圖跳轉控制 
	 */
	@Override
	public void configureViewResolvers(ViewResolverRegistry registry) {
	   // registry.viewResolver(new InternalResourceViewResolver("/jsp/", ".jsp"));
	    super.configureViewResolvers(registry);
	}
	
}
1.3 application.properties 配置
#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 及 ServiceImpl

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("當前頁:"+pageData.getPageNum());
		System.out.println("頁面大?。?quot;+pageData.getPageSize());
		System.out.println("總數(shù):"+pageData.getTotal());	
		System.out.println("總頁數(shù):"+pageData.getPages());	
		return pageData;
	}
}
1.6 Dao
public interface UserDao {
	/**
	 * 獲取所有用戶
	 * @return
	 */
	List<UserEntity> getAll();
	
}

記得在啟動類里加上**@MapperScan**

@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>
	<!-- 獲取所有用戶 -->
	<select id="getAll" resultMap="user">
		select * from t_user
	</select>
</mapper>
1.8 實體 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 頁面
<!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是一個用于Web和獨立環(huán)境的現(xiàn)代服務器端Java模板引擎。SpringBoot推薦使用Thymeleaf。</p>
<p>下面是表格示例:</p>
<table border="1">
	<thead>
		<tr>
			<th width="100">ID</th>
			<th width="100">姓名</th>
			<th width="100">性別</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'}">上一頁</a>
    
<a th:href="${'/user/list?pageNum='+(pageInfo.pageNum+1<=pageInfo.pages?pageInfo.pageNum+1:pageInfo.pages)+'&pageSize=10'}">下一頁</a>    
總數(shù):<span th:text="${pageInfo.total}"></span>
</p>
</body>
</html>

上述就是小編為大家分享的如何使用 Spring MVC和 Thymeleaf 開發(fā) web 應用了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI