SprngMVC 学习(五)视图和视图解析、转发、重定向

2017-04-19  本文已影响555人  年少懵懂丶流年梦

视图解析器

在Spring中视图相关的两个接口是ViewResolver和View两个接口。

下面是一些Spring支持的一些ViewResolver。对于其他视图技术(例如Thymeleaf)可以自己实现视图解析器以便和Spring集成。

下面是一个InternalResourceViewResolver,当我们传递一个index时,它会添加前缀和后缀,最终解析出实际的视图文件WEB-INF/jsp/index.jsp。

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>

另外Spring支持的几种视图还可以使用mvc命名空间简化。

<mvc:view-resolvers>
    <mvc:freemarker/>
    <mvc:groovy/>
    <mvc:tiles/>
    <mvc:jsp suffix=".jsp"
             prefix="/WEB-INF/jsp/"
             view-class="org.springframework.web.servlet.view.JstlView"/>

</mvc:view-resolvers>

可以定义多个视图解析器,这时候可以使用order属性指定视图解析的顺序,InternalResourceViewResolver总是最后一个视图解析器。

转发和重定向

在控制器中还可以设置转发和重定向,概念和Servlet中转发和重定向类似。

在视图名前添加redirect:前缀会重定向到该视图,这样页面和URL都会改变。
前缀forward:表示转发,内容会改变但是URL不会变。

视图

JSP和JSTL

JSP和JSTL的视图解析器配置已经在前面说了。这里就不重复了。

Thymeleaf

Thymeleaf是一个新的模板引擎,和传统的JSP相比有很多优点:

Thymeleaf和Spring的支持是由Thymeleaf团队进行的。

要添加Thymeleaf的支持,首先需要添加Thymeleaf的依赖项。在Gradle中很简单,由于thymeleaf-spring4依赖于thymeleaf-core,因此添加thymeleaf-spring4就会自动添加thymeleaf-core,非常方便。

dependencies {
    compile group: 'org.thymeleaf', name: 'thymeleaf-spring4', version: '3.0.0.RELEASE'
}
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>3.0.5.RELEASE</version>
</dependency>

之后需要配置Thymeleaf的视图解析器。对于Thymeleaf来说,还需要配置它的视图引擎和视图解析器。

<bean id="templateResolver"
      class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
    <property name="prefix" value="/WEB-INF/templates/"/>
    <property name="suffix" value=".html"/>
    <property name="templateMode" value="HTML5"/>
</bean>

<bean id="templateEngine"
      class="org.thymeleaf.spring4.SpringTemplateEngine">
    <property name="templateResolver" ref="templateResolver"/>
</bean>
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
    <property name="templateEngine" ref="templateEngine"/>
    <property name="order" value="1"/>
    <property name="characterEncoding" value="UTF-8"/>
</bean>

然后编写一个Themeleaf视图。由于Spring Web MVC的良好的分层,因此我们的代码完全不用更改就可以使用Thymeleaf视图。关于Thymeleaf的详细使用方法参见其文档

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>主页</title>
</head>
<body>
<h1>呵呵<span th:text="${name}"></span></h1>
</body>
</html>

除了这两种之外,还有很多常用的视图技术,例如FreeMarkder、Groovy标记模板等。它们的使用方法请查看相应文档。

http://www.jianshu.com/p/58ef89d90cd4

上一篇 下一篇

猜你喜欢

热点阅读