基于 Spring Boot 的 SSM 环境整合五:整合 spring mvc+thymeleaf 模板引擎

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xz2001/article/details/83826181

在开始之前,先简单介绍下 spring boot 下模版的问题:

Spring Boot提供了多种模板引擎的支持,但嵌入式容器JSP有限制,且Velocity于2010年停止更新,故JSP与Velocity两个不建议使用。Spring Boot支持的模板引擎主要有以下几种:、Thymeleaf、FreeMarker、Velocity、Groovy、Mustache、JSP。本文使用spring推荐的模板引擎 -- Thymeleaf。

1、修改 pom.xml 以引入相关资源

增加如下内容:

    <!-- thymeleaf 模板 -->
    <dependency>
      <groupId>org.springframework.boot </groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

保存后记得执行 Maven install。完整的 pom.xml如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.whowii</groupId>
  <artifactId>website_java4</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <!-- 引入spring-boot-start-parent 以提供dependency management,也就是依赖管理,引入以后在声明其它dependency的时候就不需要version了 -->
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.RELEASE</version>
  </parent>
  
  <dependencies>
  	<!-- 引入spring-boot-starter-web 以包含spring webmvc和tomcat等web开发的特性 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
      <exclusions>
        <exclusion>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    
    <!-- thymeleaf 模板 -->
    <dependency>
      <groupId>org.springframework.boot </groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
    <!-- log4j2 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>
    
    <!-- 日志工具
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-logging-juli</artifactId>
        <version>8.0.23</version>
    </dependency> -->
    
    <!-- spring mvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>website_java4</finalName>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <!-- 增加main方式启动的配置,若使用maven的spring-boot:run方式启动则不需要此配置 -->
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
        	<!-- 设置主类入口 -->
        	<mainClass>com.whowii.website4.AppBoot</mainClass>
        	<!-- 设置classpath -->
        	<addClasspath>true</addClasspath>
            <classpathPrefix>lib/</classpathPrefix>
        </configuration>
      </plugin>
    </plugins>
  </build>
  
  <properties>
  	<!-- spring 版本 -->
    <spring.version>4.3.8.RELEASE</spring.version>
    <!-- java 版本 -->
    <java.version>1.8</java.version>
  	<!-- 设置编码 -->
  	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
</project>

2、修改 spring boot 配置

修改 application.properties 以增加如下配置,以关闭模板缓存:

#关闭thymeleaf缓存,仅在开发时使用
spring.thymeleaf.cache=false
#检查模板是否存在,然后再呈现
spring.thymeleaf.check-template-location=true
#Content-Type值
spring.thymeleaf.content-type=text/html
# 在构建URL时预先查看名称的前缀
spring.thymeleaf.prefix=classpath:/templates/
# 构建URL时附加查看名称的后缀.
spring.thymeleaf.suffix=.html

修改后的 application.properties 完整内容如下:

# spring mvc 配置(视图解析器)
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp

# log4j2 配置
logging.config=classpath\:log4j2.xml

#关闭thymeleaf缓存,仅在开发时使用
spring.thymeleaf.cache=false
#检查模板是否存在,然后再呈现
spring.thymeleaf.check-template-location=true
#Content-Type值
spring.thymeleaf.content-type=text/html
# 在构建URL时预先查看名称的前缀
spring.thymeleaf.prefix=classpath:/templates/
# 构建URL时附加查看名称的后缀.
spring.thymeleaf.suffix=.html

3、增加服务层代码

第一步,在包“com.whowii.website4.admin.service”中增加接口“DemoService”,代码如下:

package com.whowii.website4.admin.service;

public interface DemoService {
	public String getHelloWorld(String username);

}

第二步,增加实现类“DemoServiceImpl”,代码如下:

package com.whowii.website4.admin.service;

import org.springframework.stereotype.Service;

@Service
public class DemoServiceImpl implements DemoService {

	@Override
	public String getHelloWorld(String username) {
		return "hello world! [" + username + "]";
	}

}

4、修改控制器以增加演示代码

修改 DemoController 增加演示代码,完成后的 DemoController 内容如下(注意其中对Controller的注解由@RestController修改为@Controller):

package com.whowii.website4.admin.controller;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.whowii.website4.admin.service.DemoService;

@Controller
@RequestMapping("/demo")
public class DemoController {
	private static final Logger logger = LogManager.getLogger(DemoController.class);
	@Autowired
	private DemoService demoService;

	@GetMapping("/index")
	public String index(Model model) {
		String username = "张三";
		String helloWorld = demoService.getHelloWorld(username);
		logger.info("用户名称为:{" + username + "},返回消息为:{" + helloWorld + "}");

		model.addAttribute("username", username);
		model.addAttribute("result", helloWorld);

		return "/admin/demo/demo-index";
	}
}

5、增加模板文件

在“src\main\resources”文件夹中增加三层文件夹“templates\admin\demo”,并在其中创建模板文件“demo-index.html”,内容如下:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>demo - index</title>
</head>
<body>
	<h1>demo-index.html - spring boot demo page</h1>
	<br/>用户名称:<span th:text="${username}"></span>
	<br/>
   	<br/>返回结果:<span th:text="${result}"></span>
</body>
</html>

6、测试结果

启动项目,打开浏览器访问“http://127.0.0.1:8080/demo/index”如下:

猜你喜欢

转载自blog.csdn.net/xz2001/article/details/83826181