您的位置:首页 > 编程语言 > Java开发

SpringMvc 集成多视图解析模版

2017-03-21 00:00 155 查看
摘要: 今天做项目要使用到两个视图解析器,网上找了半天,要么是只有配置文件,要么就是一个文字描述,都没有很清晰的描述,其中有说是配置viewNames的,搞了半天没出来,然后看了下源码:
public void setViewNames(String... viewNames) {this.viewNames = viewNames;},原来是这样..具体操作看正文。

描述:使用两个视图解析器,jsp和thymeleaf,项目使用Maven,Spring4

配置方式:

1、首先在maven中引用如下jar包:

<!-- thymeleaf模版 -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>3.0.3.RELEASE</version>
</dependency>

2、在配置文件spring-*.xml中配置(我的是spring-mybatis.xml)

<!-- JSP 视图解析器 -->
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="viewNames" value="jsp*"></property>
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
<property name="order" value="1" />
</bean>

<!-- thymeleaf 视图解析器 -->
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
<property name="viewNames" value="html*"></property>
<property name="order" value="0" />
</bean>
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
</bean>
<bean id="templateResolver" class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/frontPage/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML5" />
</bean>

3、Controller编写
(1) 使用 thymeleaf

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/api")
public class TestController {
@RequestMapping("/test")
public String getBooks(Model model){
model.addAttribute("message", "hello");
return "html/index";
}
}

(2)使用 jsp

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/login")
public class LoginController {
@RequestMapping("/loginManagement")
public String login(){
return "jsp/login/login";
}
}

4、在 html 文件中要引入这个网址

xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table>
<tbody>
<tr>
<td th:text="${message}">Red Chair</td>
</tr>
</tbody>
</table>
</body>
</html>

5、每个文件在项目中的位置

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Thymeleaf Spring