SpringMVC通過模型視圖ModelAndView渲染視圖的實現(xiàn)
SpringMVC通過模型視圖ModelAndView渲染視圖大致流程

代碼樣例
1.準備工作
A.因為文中用到jsp,所以需要引入jsp標準標簽庫standard.jar和jstl.jar
官方下載地址:http://archive.apache.org/dist/jakarta/taglibs/standard/binaries/
本地下載地址:lib_jb51.rar
B.添加Tomcat依賴如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency>
2.Web服務器發(fā)送請求
http://localhost:8080/user/details?id=12
@Controller
@Slf4j
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService = null;
@RequestMapping("details")
public ModelAndView details(Long id){
User user = userService.getUser(id);
log.info("獲取到的user對象-->"+user.toString());
ModelAndView mv = new ModelAndView();//新建一個模型和視圖對象
mv.setViewName("user/details");//設置模型視圖名稱
mv.addObject("user",user);//加入數(shù)據(jù)模型
return mv;//返回視圖和模型
}
}
A.根據(jù)請求路徑/user/details通過HandlerMapper機制就能找到對應的控制器進行響應。返回一個HandlerExecutionChain對象,而HandlerExecutionChain對象中的handler(處理器)需要運行,需要處理器適配器HandlerAdapter接口定義的實現(xiàn)類。
B.在處理器調用控制器(controller)時,先通過模型層得到數(shù)據(jù),再放入數(shù)據(jù)模型中,最后返回模型和視圖對象。這里的模型視圖名稱為user/details,走到視圖解析器(ViewResolver),解析視圖邏輯名稱。
spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp
C.為了定制InternalResourceViewResolver初始化,可以在配置文件application.properties(或yml文件)中進行配置,代碼如上。
D.它會以前綴(prefix)和后綴(suffix)以及視圖名稱組成全路徑定位視圖。
此例組成的全路徑為:/WEB-INF/jsp/user/details.jsp

jsp存放位置如上:
<%@ page pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>用戶詳情</title>
</head>
<body>
<center>
<table border="1">
<tr>
<td>標簽</td>
<td>值</td>
</tr>
<tr>
<td>用戶編號</td>
<td><c:out value="${user.id}"></c:out></td>
</tr>
<tr>
<td>用戶名稱</td>
<td><c:out value="${user.userName}"></c:out></td>
</tr>
<tr>
<td>用戶備注</td>
<td><c:out value="${user.note}"></c:out></td>
</tr>
</table>
</center>
</body>
</html>
E.視圖解析器定位到視圖后,視圖的作用就是將數(shù)據(jù)模型渲染。這樣就能看到結果
到此這篇關于SpringMVC通過模型視圖ModelAndView渲染視圖的實現(xiàn)的文章就介紹到這了,更多相關SpringMVC ModelAndView渲染視圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
@CacheEvict中的allEntries與beforeInvocation的區(qū)別說明
這篇文章主要介紹了@CacheEvict中的allEntries與beforeInvocation的區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12

