這期內(nèi)容當(dāng)中小編將會給大家?guī)碛嘘P(guān)如何使用 Spring MVC和 Thymeleaf 開發(fā) web 應(yīng)用,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
為北川羌族等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計制作服務(wù),及北川羌族網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為成都網(wǎng)站設(shè)計、做網(wǎng)站、北川羌族網(wǎng)站設(shè)計,以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會得到認(rèn)可,從而選擇與我們長期合作。這樣,我們也可以走得更遠(yuǎn)!
Spring MVC 是構(gòu)建在 Servlet API 上的原生框架,并從一開始就包含在 Spring 框架中。本文主要通過簡述 Spring MVC 的架構(gòu)及分析,并用 Spring Boot + Spring MVC + MyBatis (SSM)+ Thymeleaf(模板引擎) 框架來簡單快速構(gòu)建一個 Web 項(xiàng)目。
MVC 三層架構(gòu)如圖所示,紅色字體代表核心模塊。其中 MVC 各分層分別為:
**Model (模型層)**處理核心業(yè)務(wù)(數(shù)據(jù))邏輯,模型對象負(fù)責(zé)在數(shù)據(jù)庫中存取數(shù)據(jù)。這里的“數(shù)據(jù)”不僅限于數(shù)據(jù)本身,還包括處理數(shù)據(jù)的邏輯。
**View(視圖層)**用于展示數(shù)據(jù),通常數(shù)據(jù)依據(jù)模型數(shù)據(jù)創(chuàng)建。
**Controller(控制器層)**用于處理用戶輸入請求和響應(yīng)輸出,從試圖讀取數(shù)據(jù),控制用戶輸入,并向模型發(fā)送數(shù)據(jù)。Controller 是在 Model 和 View 之間雙向傳遞數(shù)據(jù)的中間協(xié)調(diào)者。
Spring MVC 處理一個 HTTP 請求的流程,如圖所示: 整個過程詳細(xì)介紹: 1.用戶發(fā)送請求至前端控制器 DispatcherServlet。 2.DispatcherServlet 收到請求調(diào)用處理器映射器 HandlerMapping。 3.處理器映射器根據(jù)請求 URL 找到具體的 Controller 處理器返回給 DispatcherServlet。 4.DispatcherServlet 通過處理器適配器 HandlerAdapter 調(diào)用 Controller 處理請求。 5.執(zhí)行 Controller 處理器的方法。 6.Controller 執(zhí)行完成返回 ModelAndView。 7.HandlerAdapter 將 Controller 執(zhí)行結(jié)果 ModelAndView 返回給 DispatcherServlet。 8.DispatcherServlet 將 ModelAndView 的 ViewName 傳給視圖解析器 ViewReslover。 9.ViewReslover 解析后返回具體的視圖 View。 10.DispatcherServlet 傳遞 Model 數(shù)據(jù)給 View,對 View 進(jìn)行渲染(即將模型數(shù)據(jù)填充至視圖中)。 11-12.DispatcherServlet 響應(yīng)用戶。
本段我們主要通過構(gòu)建項(xiàng)目,實(shí)現(xiàn)一個分頁查詢。
項(xiàng)目結(jié)構(gòu)如圖所示:
<?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ù)據(jù)庫驅(qū)動. --> <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>
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");//設(shè)置默認(rèn)跳轉(zhuǎn)視圖為 /index registry.setOrder(Ordered.HIGHEST_PRECEDENCE); super.addViewControllers(registry); } /** * 視圖解析器配置 控制controller String返回的頁面 視圖跳轉(zhuǎn)控制 */ @Override public void configureViewResolvers(ViewResolverRegistry registry) { // registry.viewResolver(new InternalResourceViewResolver("/jsp/", ".jsp")); super.configureViewResolvers(registry); } }
#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
@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; } }
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("當(dāng)前頁:"+pageData.getPageNum()); System.out.println("頁面大?。?quot;+pageData.getPageSize()); System.out.println("總數(shù):"+pageData.getTotal()); System.out.println("總頁數(shù):"+pageData.getPages()); return pageData; } }
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); } }
<?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>
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; } }
<!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和獨(dú)立環(huán)境的現(xiàn)代服務(wù)器端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īng)用了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
分享文章:如何使用SpringMVC和Thymeleaf開發(fā)web應(yīng)用
當(dāng)前路徑:http://aaarwkj.com/article44/jesohe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站設(shè)計、網(wǎng)站營銷、網(wǎng)站制作、小程序開發(fā)、網(wǎng)站內(nèi)鏈、App開發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)