【Spring Boot系列学习】03.web应用模板引擎(jsp,freemarker,Thymeleaf)

Spring Boot提供了spring-boot-starter-web为Web开发予以支持,spring-boot-starter-web为我们提供了嵌入的Tomcat以及Spring MVC的依赖。

模板引擎

Spring Boot支持多种模版引擎包括:FreeMarker、Groovy、Thymeleaf(官方推荐)、Mustache、JSP(官方不推荐)
jsp官方不推荐原因:

  1. tomcat只支持war的打包方式,不支持可执行的jar。
  2. Jetty 嵌套的容器不支持jsp
  3. Undertow
  4. 创建自定义error.jsp页面不会覆盖错误处理的默认视图,而应该使用自定义错误页面

在spring boot应用中,默认模板配置路径为:src/main/resources/templates,可通过配置文件修改该路径。 

一、模板引擎_JSP

1.项目结构

推荐使用这样式的目录结构,新增了webapp这个用来存放jsp的目录,静态资源还是放在resources目录下。

2.引入依赖

<!--WEB支持-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!--jsp页面使用jstl标签-->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
</dependency>

<!--用于编译jsp-->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>

3.application.properties配置

若需要支持jsp,需在配置文件中配置返回文件的路径及后缀(类型)

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

4.编写响应的控制类及其他代码

其中控制类的编写与普通spring mvc代码一样。
控制器代码:


@Controller
@RequestMapping("/book")
public class BookController {
    @RequestMapping("")
    public ModelAndView index(){
        System.out.println("-------------------------test---");
        List<Book> learnList =new ArrayList<Book>();
        Book bean =new Book("官方参考文档","Spring Boot Reference Guide","http://docs.spring.io/spring-boot/docs/1.5.1.RELEASE/reference/htmlsingle/#getting-started-first-application");
        learnList.add(bean);
        bean =new Book("官方SpriongBoot例子","官方SpriongBoot例子","https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples");
        learnList.add(bean);
        bean =new Book("龙国学院","Spring Boot 教程系列学习","http://www.roncoo.com/article/detail/125488");
        learnList.add(bean);

        ModelAndView modelAndView = new ModelAndView("index");
        modelAndView.addObject("learnList", learnList);

        return modelAndView;
    }
}

jsp代码:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<div class="body_wrap">
    <div class="container">
        <div class="alert alert-success text-center" role="alert">Sptring Boot学习</div>
        <table class="table table-striped table-bordered">
            <tr>
                <td>作者</td>
                <td>教程名称</td>
                <td>地址</td>
            </tr>
            <c:forEach var="learn" items="${learnList}">
                <tr class="text-info">
                    <td >${learn.author}</td>
                    <td >${learn.bookName}</td>
                    <td><a href="${learn.bookurl}" class="btn btn-search btn-green" target="_blank"><span>点我</span></a>
                    </td>
                </tr>
            </c:forEach>
        </table>
    </div>
</div>
</body>
</html>

在该过程中需注意的是:
1).idea默认是不支持jsp的,所以当我们新建jsp页面时,是没有模板的,需要对其操作如下:选择File-》点击project Structure项,在Modules选项卡中,找到当前项目,在本项目下添加web。并修改其配置信息。

修改其路径为当前项目的webapp目录。
参考:https://www.cnblogs.com/sxdcgaq8080/p/7676294.html

5.项目启动

5.1内嵌Tomcat启动运行项目

5.1.1启动方式:我试了两种启动方式

1).直接右键启动项目,浏览器访问时,会提示404错误,其原因在于pom文件中<scope>provided</scope>.

2).第二种方式是打开Maven Projects-》Plugins-》spring-boot-》spring-boot:run,启动项目,访问成功。

其他启动方式及访问结果参考http://tengj.top/2017/03/13/springboot5/#

5.1.2内置Tomcat及Servlet配置

配置信息一般都配置在application.properties文件中,通用的Servlet容器的配置都用“server”作为前缀,tomcat特有配置则以“server.tomcat”作为前缀。一般配置如:
Servlet容器配置

#配置程序端口,默认为8080
server.port= 8080
#用户绘画session过期时间,以秒为单位
server.session.timeout=
# 配置默认访问路径,默认为/
server.context-path=

Tomcat配置

# 配置Tomcat编码,默认为UTF-8
server.tomcat.uri-encoding=UTF-8
# 配置最大线程数
server.tomcat.max-threads=1000

5.2外部Tomcat部署项目War包

如需将springboot项目部署在外部Tomcat中,若直接导出为war包部署,是会报错的,需要进行如下操作后,才可以。

1).入口类继承SpringBootServletInitializer并实现configure方法。
类似于web.xml的方式来启动spring应用上下文。等同于web.xml中负责初始化spring应用的监听器类似。

public class Application extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }
}

2).修改pom.xml配置文件(若要将最终打包方式改为war)
因为spring-boot-starter-web中包含内嵌的tomcat容器,所以直接部署在外部容器会冲突报错.

参考:http://tengj.top/2017/03/13/springboot5/#

二、模板引擎_Thymeleaf

Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等,与其它模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。即在本地环境或者有网络的环境下,Thymeleaf 均可运行。在静态页面时,会展示静态信息,当服务启动后,动态获取数据库中的数据后,就可以展示动态数据。

  • Spring MVC中@Controller中的方法可以直接返回模板名称,接下来Thymeleaf模板引擎会自动进行渲染
  • 模板中的表达式支持Spring表达式语言(Spring EL)
  • 表单支持,并兼容Spring MVC的数据绑定与验证机制
  • 国际化支持

0.Thymeleaf

1).在HTML页面中导入名称空间

<html xmlns:th="http://www.thymeleaf.org">

2).在标签中使用Thymeleaf

1.项目结构

2.引入依赖

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

此时application.properties配置文件中默认的配置如下,如有不同,按需修改即可。

##thymeleaf的默认配置
spring.thymeleaf.cache=true ##Thymeleaf 默认是开启页面缓存的,所以在开发的时候,需要关闭这个页面缓存,否则会有缓存,导致页面没法及时看到更新后的效果。
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html

3.控制类代码

3.1与jsp中的控制类代码一样。

3.2控制器代码也可以如下

@Controller
@RequestMapping("thymeleaf")
public class ThymeleafController {
    @RequestMapping("hello")
    public String hello(Map<String,Object> map) {
        map.put("msg", "Hello Thymeleaf");
        return "hello";
    }
}

4.前端html代码(模板代码)

即编写前端模板代码。

4.1根据3.1实例代码如下

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Resources</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div style="text-align: center;margin:0 auto;width: 1000px; ">
    <h1>学习资源</h1>
    <table width="100%" border="1" cellspacing="1" cellpadding="0">
        <tr>
            <td>作者</td>
            <td>教程名称</td>
            <td>地址</td>
        </tr>
        <tr  th:each="book,iterStat : ${learnList}">
            <td th:text="${book.author}">author</td>
            <td th:text="${book.bookName}">bookName</td>
            <td><a th:href="${book.bookurl}" >bookurl</a> </td>
        </tr>
    </table>
</div>
</body>
</html>

静态页面效果:

动态效果:

同样,也需要注意启动方式。

4.2根据3.2的前端实例

在 template 目录下创建名为 hello.html 的文件

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link href="/css/index.css" rel="stylesheet"/>
</head>
<body>
    <div class="container">
        <h2 th:text="${msg}"></h2>
    </div>
</body>
</html>

4.3 thymeleaf 常见操作

1.当controller中返回的数据中包含对象的时候,thymeleaf的处理方式是:

thymeleaf 模板中,使用 th:object="${}" 来获取对象信息,然后通过如下方式获取对象属性
使用 th:value="*{ 属性名 }"
使用 th:value="${ 对象 . 属性名 }" ,对象指的是上面使用 th:object 获取的对象
使用 th:value="${ 对象 .get 方法 }" ,对象指的是上面使用 th:object 获取的对象
 
标签
功能例子
th:value给属性赋值<input th:value="${blog.name}" />
th:style设置样式
th:style="'display:'+@{(${sitrue}?'none':'inline - block')} +
''"
th:onclick
点击事件th:οnclick="'getInfo()'"
th:if
条件判断<a th:if="${userId == collect.userId}" >
th:href
超链接<a th:href="@{/blogger/login}">Login</a> />
th:unless
条件判断和
th:if 相反
<a th:href="@{/blogger/login}" th:unless=${session.user !=
null}>Login</a>
th:switch
配合 th:case<div th:switch="${user.role}">
th:case
配合 th:switch<p th:case="'admin'">administator</p>
th:src
地址引入<img alt="csdn logo" th:src="@{/img/logo.png}" />
th:action
表单提交的地址<form th:action="@{/blogger/update}">

 

 
 
 
 

三、模板引擎_Freemarker

1.添加 Freemarker 依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

2.添加 Freemarker 模板配置

在 application.properties 中添加如下内容,不填也可以,默认是如下配置

spring.freemarker.allow-request-override=false
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
spring.freemarker.prefix=
spring.freemarker.suffix=.ftl

3.控制器代码

@Controller
@RequestMapping("freemarker")
public class FreemarkerController {
    @RequestMapping("hello")
    public String hello(Map<String,Object> map) {        
        map.put("msg", "Hello Freemarker");
        return "hello";
    }
}

4.在 templates 目录中创建名为 hello.ftl 文件

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link href="/css/index.css" rel="stylesheet"/>
</head>
<body>
    <div class="container">
        <h2>${msg}</h2>
    </div>
</body>
</html>

说明:

【注】微服务中会走向前后端分离,在Controller 层上都是使用的 @RestController 注解,自动会把返回的数据转成 json 格式。但是在使用模板引擎时, Controller 层就不能用 @RestController 注解了,因为在使用 thymeleaf 模板(或其他)时,返回的是视图文件名,比如 Controller 中某个方法返回“index”,指的是返回到 index.html 页面,如果使用 @RestController 的话,会把 index 当作 String 解析了,直接返回到页面了,而不是去找 index.html 页面。所以在使用模板时要用 @Controller 注解。
 

参考:http://tengj.top/2017/03/13/springboot5/#

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值