SpringMVC 學習(五)——檢視和檢視解析器
Spring MVC如何解析檢視
檢視和檢視解析器
•請求處理方法執行完成後,最終返回一個 ModelAndView 對象。對於那些返回 String,View 或 ModeMap 等類型的 處理方法,Spring MVC 也會在內部將它們裝配成一個
ModelAndView 對象,它包含了邏輯名和模型對象的檢視
•Spring MVC 藉助檢視解析器(ViewResolver)得到最終 的檢視對象(View),最終的檢視可以是 JSP ,也可能是
Excel、JFreeChart
•對於最終究竟採取何種檢視對象對模型資料進行渲染,處 理器並不關心,處理器工作重點聚焦在生產模型資料的工 作上,從而實現 MVC 的充分解耦
檢視
•檢視的作用是渲染模型資料,將模型裡的資料以某種形式呈現給客 戶。
•為了實現檢視模型和具體實現技術的解耦,Spring 在
org.springframework.web.servlet 包中定義了一個高度抽象的 View
介面:
•檢視對象由檢視解析器負責實例化。由於檢視是無狀態的,所以他們
不會有線程安全的問題
常用的檢視實現類
檢視
•SpringMVC 為邏輯檢視名的解析提供了不同的策略,可 以在 Spring WEB 上下文中配置一種或多種解析策略,並 指定他們之間的先後順序。每一種對映策略對應一個具體 的檢視解析器實現類。
•檢視解析器的作用比較單一:將邏輯檢視解析為一個具體 的檢視對象。
•所有的檢視解析器都必須實現 ViewResolver 介面:
常用的檢視解析器實現類
•程式員可以選擇一種檢視解析器或混用多種檢視解析器
•每個檢視解析器都實現了 Ordered 介面並開放出一個 order 屬性,可 以通過 order 屬性指定解析器的
•SpringMVC 會按檢視解析器順序的優先順序對邏輯檢視名進行解
析,直到解析成功並返回檢視對象,否則將丟擲 ServletException 異
常
InternalResourceViewResolver
•JSP 是最常見的檢視技術,可以使用
InternalResourceViewResolver 作為檢視解析器:
InternalResourceViewResolver
•若項目中使用了 JSTL,則 SpringMVC 會自動把檢視由
InternalResourceView 轉為 JstlView
•若使用 JSTL 的 fmt 標籤則需要在 SpringMVC 的配置檔案中配置國際 化資原始檔
•若希望直接響應通過 SpringMVC 渲染的頁面,可以使用 mvc:view-
controller 標籤實現
Excel 檢視
•若希望使用 Excel 展示資料列表,僅需要擴展
SpringMVC 提供的 AbstractExcelView 或 AbstractJExcel View 即可。實現 buildExcelDocument() 方法,在方法中使用模型資料對象構建 Excel 文件就可以 了。
•AbstractExcelView 基於 POI API,而
AbstractJExcelView 是基於 JExcelAPI 的。
•檢視對象需要配置 IOC 容器中的一個 Bean,使用
BeanNameViewResolver 作為檢視解析器即可
•若希望直接在瀏覽器中直接下載 Excel 文件,則可以設置 響應頭 Content-Disposition 的值為 attachment;filename=xxx.xls
關於重定向
•一般情況下,控制器方法返回字串類型的值會被當成邏 輯檢視名處理
•如果返回的字串中帶 forward: 或 redirect: 前綴
時,SpringMVC 會對他們進行特殊處理:將 forward: 和
redirect: 當成指示符,其後的字串作為 URL 來處理
–redirect:success.jsp:會完成一個到 success.jsp 的重定向的操作
–forward:success.jsp:會完成一個到 success.jsp 的轉發操作
test,java
package com.xuehj.springmvc.handler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
/**
* @program: SpringMVC
* @description: TODO
* @author: Mr.Xue
* @create: 2018-12-24 09:36
**/
@SessionAttributes(value = {"user"}, types = {String.class})
@Controller
@RequestMapping("/view")
public class HelloWorld {
@RequestMapping("/testViewAndViewResolver")
public String testViewAndViewResolver(){
System.out.println("testViewAndViewResolver");
return "success.jsp";
}
@RequestMapping("/testView")
public String testView(){
System.out.println("testView");
return "helloView";
}
@RequestMapping("/testRedirect")
public String testRedirect(){
System.out.println("testRedirect");
return "redirect:/index.jsp";
}
}
helloview.java
package com.xuehj.springmvc.view;
import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @program: SpringMVC-1
* @description: TODO
* @author: Mr.Xue
* @create: 2018-12-25 01:53
**/
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.View;
@Component
public class HelloView implements View {
@Override
public String getContentType() {
return "text/html";
}
@Override
public void render(Map<String, ?> model, HttpServletRequest request,
HttpServletResponse response) throws Exception {
response.getWriter().print("hello view, time: " + new Date());
}
}
success.jsp
<%@ taglib prefix="fmt" uri="http://www.springframework.org/tags" %>
<%--<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>--%>
<%--
Created by IntelliJ IDEA.
User: 薛恆傑
Date: 2018/12/24
Time: 9:39
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>Hello World</h1>
<fmt:message code="i18n.username"/>
<br><br>
<fmt:message code="i18n.password"/>
<br><br>
</body>
</html>
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 配置自定掃描的包 -->
<context:component-scan base-package="com.xuehj.springmvc"/>
<!-- 配置檢視解析器: 如何把 handler 方法返回值解析為實際的物理檢視 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--<property name="prefix" value="/view/"/>-->
<!--<property name="suffix" value=".jsp"/>-->
<property name="prefix" value=""/>
<property name="suffix" value=""/>
</bean>
<!-- 配置檢視 BeanNameViewResolver 解析器: 使用檢視的名字來解析檢視 -->
<!-- 通過 order 屬性來定義檢視解析器的優先順序, order 值越小優先順序越高 -->
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
<property name="order" value="100"/>
</bean>
<!-- 配置國際化資原始檔 -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="i18n"/>
</bean>
<!-- 配置直接轉發的頁面 -->
<!-- 可以直接相應轉發的頁面, 而無需再經過 Handler 的方法. -->
<mvc:view-controller path="/success" view-name="/view/success.jsp"/>
<!-- 在實際開發中通常都需配置 mvc:annotation-driven 標籤 -->
<mvc:annotation-driven/>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--
配置 org.springframework.web.filter.HiddenHttpMethodFilter: 可以把 POST 請求轉為 DELETE 或 PUT 請求
-->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置 DispatcherServlet -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置 DispatcherServlet 的一個初始化引數: 配置 SpringMVC 配置檔案的位置和名稱 -->
<!--
實際上也可以不通過 contextConfigLocation 來配置 SpringMVC 的配置檔案, 而使用預設的.
預設的配置檔案為: /WEB-INF/<servlet-name>-servlet.xml
-->
<!--
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
index.jsp
<%--
Created by IntelliJ IDEA.
User: 薛恆傑
Date: 2018/12/24
Time: 9:21
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<a href="view/testViewAndViewResolver">Test ViewAndViewResolver</a>
<br><br>
<a href="view/testView">Test View</a>
<br><br>
<a href="view/testRedirect">Test Redirect</a>
<br><br>
</body>
</html>