springboot配置server相关配置&整合模板引擎Freemarker、thymeleaf&thymeleaf基本用法

1.Springboot配置server相关配置(包括默认tomcat的相关配置)

  下面的配置也都是模板,需要的时候在application.properties配置即可

############################################################
#
# Server 服务端相关配置
#
############################################################
# 配置api端口号
server.port=8088
# 配置context-path, 一般来说这个配置在正式发布的时候不配置
server.context-path=/MySpringboot
# 错误页,指定发生错误时,跳转的URL --> BasicErrorController
#server.error.path=/error
# session最大超时时间(分钟),默认为30分钟
server.session-timeout=60
# 该服务绑定IP地址,启动服务器时如本机不是该IP地址则抛出异常启动失败, 
# 只有特殊需求的情况下才配置, 具体根据各自的业务来设置
#server.address=192.168.1.2

############################################################
# Server - tomcat 相关常用配置
############################################################
# tomcat最大线程数, 默认为200
#server.tomcat.max-threads=250
# tomcat的URI编码
server.tomcat.uri-encoding=UTF-8
# 存放Tomcat的日志、Dump等文件的临时文件夹,默认为系统的tmp文件夹
#(如:C:%users\Shanhy\AppData\Local\Temp)
#server.tomcat.basedir=H:/springboot-tomcat-tmp
# 打开Tomcat的Access日志,并可以设置日志格式的方法:
#server.tomcat.access-log-enabled=true
#server.tomcat.access-log-pattern=
# accesslog目录,默认在basedir/logs
#server.tomcat.accesslog.directory=
# 日志文件目录
#logging.path=H:/springboot-tomcat-tmp
# 日志文件名称,默认为spring.log
#logging.file=myapp.log

例如上面我简单的修改了一下默认的端口与contextPath等信息,启动测试:

2.整合模板引擎

   springboot提倡的方式是整合freemarker和thymeleaf。之前用普通项目的时候都是用的JSP,实际上JSP是一种servlet,需要在后台渲染页面之后在前台进行展示,所以比较耗时。而引擎相对于JSP来说就比较省时。引擎常用的有freemarker和thymeleaf,在项目中可以两种一起结合使用,但是一般有一种就足够了。

2.1整合Freemarker引擎

   freemarker的文件一般后缀是 ftl,关于freemarker的基本使用参考我的freemarker标签博客即可。

 (1)首先pom中引入freemarker引擎

        <!-- 引入 freemarker 模板依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

 (2)application.properties引入freemarker相关配置:

############################################################
#
# freemarker 静态资源配置
#
############################################################
#设定ftl文件路径
spring.freemarker.template-loader-path=classpath:/templates
# 关闭缓存, 即时刷新, 上线生产环境需要改为true
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
spring.freemarker.request-context-attribute=request
spring.freemarker.suffix=.ftl

 (3)编写后台Controller

package cn.qlq.action;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 返回freemarker相关页面
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping("freemarker")
public class FreemarkerController {

    /**
     * 会跳转到templates/freemarker/index.ftl
     * 
     * @param map
     * @return
     */
    @RequestMapping("/index")
    public String index(ModelMap map) {
        map.addAttribute("name", "testname");
        return "freemarker/index";
    }

    /**
     * 会跳转到templates/freemarker/center/center.ftl
     * 
     * @return
     */
    @RequestMapping("/center")
    public String center() {
        return "freemarker/center/center";
    }
}

(4)建立模板结构:

index.ftl内容如下:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title>FreeMarker模板引擎</title>
</head>
<body>
FreeMarker模板引擎
<h1>${name}</h1>
</body>
</html>

center.ftl内容如下:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
FreeMarker模板引擎
<h1>center page</h1>
</body>
</html>

启动项目进行测试:

 

2.2整合thymeleaf引擎

  thymeleaf文件的后缀是html。这种方式也适用于前后端分离。

 (1)首先pom中引入thymeleaf引擎

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

 (2)applications.properties引入配置:

############################################################
#
# 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
# 关闭缓存, 即时刷新, 上线生产环境需要改为true
spring.thymeleaf.cache=false

 (3)编写后台Controller

package cn.qlq.action;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 返回freemarker相关页面
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping("th")
public class ThymeleafController {

    /**
     * 会跳转到templates/freemarker/index.html
     * 
     * @param map
     * @return
     */
    @RequestMapping("/index")
    public String index(ModelMap map) {
        map.addAttribute("name", "testname");
        return "thymeleaf/index";
    }

    /**
     * 会跳转到templates/thymeleaf/center/center.html
     * 
     * @return
     */
    @RequestMapping("/center")
    public String center() {
        return "thymeleaf/center/center";
    }
}

(4)编写界面:

 

center.html: (一个静态的页面)

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
Thymeleaf模板引擎
<h1>center page</h1>
</body>
</html>

 index.html(下面这个试用于前后端分离,也就是说在后端没有返回数据的时候h1显示的是中间的hello word ~~~ ,如果有数据了会用${name}取到的值取代两个标签中间的内容)

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
Thymeleaf模板引擎
<h1 th:text="${name}">hello world~~~~~~~</h1>
</body>
</html>

单独访问这个index.html效果如下:

 (5)启动测试:

 

3.thymeleaf常用标签用法(如果会用可以不看下面例子)

  官方文档:https://www.thymeleaf.org/documentation.html

     下面都是针对的动态数据的方式(数据从后台返回到前台的方法),如果是静态方式使用方法同以前普通的html的使用方法一样。  

1.基本使用方式

  th:id="${id}"  th:name="${name}"   th:value="${name}"   等标签如果取到属性就会取代原来界面上的对应的属性。

例如对于如下页面:

用户姓名:<input id="id" name="name"  value="value" th:id="${user.username}" th:name="${user.username}" th:value="${user.username}"/>

(1)查看静态页面

(2)经过后台的渲染页面

 

2.对象引用方式

   如下面写法:

<div th:object="${user}">
    用户姓名:<input th:id="*{username}" th:name="*{username}" th:value="*{username}"/>
    <br/>
    用户生日:<input th:value="*{#dates.format(birthday, 'yyyy-MM-dd hh:mm:ss')}"/>
    <br/>
</div>

3.时间类型转换

    <br/>
    用户生日:<input th:value="${user.birthday}"/>
    <br/>
    用户生日:<input th:value="${#dates.format(user.birthday, 'yyyy-MM-dd')}"/>

 界面查看:

4.th:text与th:utext

  th:text会将后台传回来的字符串原封不动的替换标签中的内容为后台返回的内容

  th:utext会解析后台传回来的内容中的html标签,也就是这个会解析html标签。

如下:后台设置地址为:

user.setAddress("<font color='red'>中国<font>");

前台代码:

text 与 utext :<br/>
<span th:text="${user.address}">abc</span>
<br/>
<span th:utext="${user.address}">abc</span>

结果:

5.URL

  URL的用法是: @{url}。

例如:

URL:<br/>
<a href="http://www.baidu.com" th:href="@{${user.address}}">网站地址</a>
<br/>

结果:

6.引入静态资源文件js/css

如果引入静态文件需要在applications.properties文件中进行配置放开静态文件:

#设定静态文件路径,js,css等
spring.mvc.static-path-pattern=/static/**

对应的目录结构:

页面引入JS的方法:

<script th:src="@{/static/js/test.js}"></script>

7.条件判断 th:if   th:unless与th:if

th:if 相当于 JSTL的<:if>标签,判断等于直接用 == ,大于用ge(grater than),大于等于用ge(grater or equal)。。。。。。

th:unless是if的取反

<br/>
<div th:if="${user.id} == 18">十八岁的天空</div>
<div th:if="${user.id} gt 18">你老了</div>
<div th:if="${user.id} lt 18">你很年轻</div>
<div th:if="${user.id} ge 18">大于等于</div>
<div th:if="${user.id} le 18">小于等于</div>
<br/>

<br/>
<div th:unless="${user.id} == 18">十八岁的天空</div>
<div th:unless="${user.id} gt 18">你老了</div>
<div th:unless="${user.id} lt 18">你很年轻</div>
<div th:unless="${user.id} ge 18">大于等于</div>
<div th:unless="${user.id} le 18">小于等于</div>
<br/>

后台设置id为2查看结果页面填充结果:

8.循环 

  th:each相当于<c:foreach....>

<br/>
<table>
    <tr>
        <th>姓名</th>
        <th>性别</th>
        <th>id描述</th>
        <th>生日</th>
    </tr>
    <tr th:each="person:${userList}">
        <td th:text="${person.username}"></td>
        <td th:text="${person.sex}"></td>
        <td th:text="${person.id gt 18} ? id大于18 : id小于18">18岁</td>
        <td th:text="${#dates.format(user.birthday, 'yyyy-MM-dd hh:mm:ss')}"></td>
    </tr>
</table>
<br/>

 后台:

    @RequestMapping("/test")
    public String test(ModelMap map) {
        User user = new User();
        user.setId(2);
        user.setSex("nv");
        user.setUsername("lisi");
        user.setAddress("http://qiaoliqiang.cn");
        user.setBirthday(new Date());
        map.addAttribute("user", user);
        
        User user2 = user;
        List<User> userList = new ArrayList<>();
        userList.add(user);
        userList.add(user2);
        
        map.addAttribute("userList", userList);
        return "thymeleaf/test";
    }

前台填充后结果:

9.th:switch与th:case

   相当于java的switch 。。。 case 语句

<div th:switch="${user.username}">
  <p th:case="'zhangsan'">zhangsan</p>
  <p th:case="'lisi'">lisi</p>
  <p th:case="*">其他用户</p>
</div>

10. #{}读取资源文件 properties文件 (不能直接读取,需要结合th标签使用)

(1)applications.properties文件中配置资源文件

############################################################
#
# 配置i18n 资源文件,供thymeleaf 读取
#
############################################################
spring.messages.basename=i18n/messages
spring.messages.cache-seconds=3600
spring.messages.encoding=UTF-8

(2)建立相应文件:

messages.properties内容如下:

############################################################
#
# 用户自定义权限
#
############################################################
# 普通管理员
roles.manager=manager
roles.superadmin=superadmin

(3)页面使用#{key}读取即可

<p th:utext="#{roles.manager}">xxxxxxx</p>

结果:

manager 

11.表单提交

<form th:action="@{/th/postform}" th:object="${user}" method="post" th:method="post">
    <input type="text" th:field="*{username}"/>
    <input type="text" th:field="*{address}"/>
    <input type="submit"/>
</form>

查看填充后的源码:

 th:object="${user}"是上面介绍的对象引用的方式,

 th:field="*{username}"相当于  id="username"  name="username" value="${username}"

 后台接受的方法:(重定向到 /th/test )

    /**
     * 
     * @return
     */
    @RequestMapping("/postform")
    public String postform(User user) {
        System.out.println(user.getUsername());
        System.out.println(user.getAddress());
        return "redirect:/th/test";
    }

12.下拉选择框的默认选中与单选框的选中:

<br/>
<select>
     <option >选择框</option>
     <option th:selected="${user.username eq 'zhangsan'}">zhangsan</option>
     <option th:selected="${user.username eq 'lisi'}">lisi</option>
     <option th:selected="${user.username eq 'wangwu'}">wangwu</option>
</select>
<br/>

<br/>
<input type="radio" th:checked="${user.sex eq 'nan'}"/><input type="radio" th:checked="${user.sex eq 'nv'}"/><br/>

 后台:

    @RequestMapping("/test")
    public String test(ModelMap map) {
        User user = new User();
        user.setId(2);
        user.setSex("nv");
        user.setUsername("lisi");
        user.setAddress("http://qiaoliqiang.cn");
        user.setBirthday(new Date());
        map.addAttribute("user", user);

        return "thymeleaf/test";
    } 

前台填充后结果:

猜你喜欢

转载自www.cnblogs.com/qlqwjy/p/10400489.html