1. 程式人生 > >SpringMVC 學習(五)——檢視和檢視解析器

SpringMVC 學習(五)——檢視和檢視解析器

Spring MVC如何解析檢視

 

 

 

檢視檢視解析器

 

 

理方法行完成後,最返回一個 ModelAndView  象。於那些返回 StringView ModeMap 型的 理方法,Spring MVC 也會在內部將它裝配成一個

ModelAndView ,它包含了邏輯名和模型象的檢視

Spring MVC 藉助檢視解析器ViewResolver得到最檢視對View),檢視可以是 JSP ,也可能是

ExcelJFreeChart 

等各形式的檢視

於最究竟採取何種檢視對模型資料染,理器並不心,理器工作重點聚焦在生模型資料的工 作上,從而實現 MVC 的充分解

 

檢視

檢視的作用是染模型資料,將模型裡的資料以某形式呈現給

實現檢視模型和具體實現的解Spring

org.springframework.web.servlet 包中定了一個高度抽象的 View

介面:

檢視對象由檢視解析器負責實例化。由於檢視無狀的,所以他

不會有程安全問題

 

常用的檢視實現類

檢視

解析器

SpringMVC 為邏輯檢視名的解析提供了不同的策略,可 以在 Spring WEB 上下文中配置一或多解析策略並 指定他的先後對映策略對應一個具體 的檢視解析器實現類

檢視解析器的作用比較單一:將邏輯檢視解析一個具體 的檢視對象。

所有的檢視解析器都必須實現 ViewResolver 介面:

 

常用的檢視解析器實現類

 

程式可以選擇種檢視解析器或混用多種檢視解析器

檢視解析器都實現 Ordered 介面並放出一個 order 屬性,可 以通 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>