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等信息,启动测试:

freemarker下标获取_后端

 

2.整合模板引擎

注意applications.properties文件中两者的前缀一个最后加/一个不加。

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)建立模板结构:

freemarker下标获取_freemarker下标获取_02

 

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>



 

 

启动项目进行测试:

freemarker下标获取_ViewUI_03

 

 

freemarker下标获取_ViewUI_04

2.2整合thymeleaf引擎

 这种方式也适用于前后端分离。

 (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)编写界面:

 

freemarker下标获取_后端_05

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



<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
Thymeleaf模板引擎
<h1>center page</h1>
</body>
</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效果如下:

freemarker下标获取_java_06

 

 (5)启动测试:

 

freemarker下标获取_freemarker下标获取_07

freemarker下标获取_javascript_08

 

3.thymeleaf 获取项目路径 contextPath

1.页面通过标签获取:



<span th:text="${#httpServletRequest.getContextPath()}">abc</span>



如下:



<a th:href="${#httpServletRequest.getContextPath()+'/index.html'}">XXX</a>



结果:

freemarker下标获取_freemarker下标获取_09

 

2.通过JS获取



<script th:inline="javascript">     
        var contextPath= [[@{/}]];      
</script>



 

关于项目中路径带根路径的URL的写法如下:



<link rel="stylesheet" th:href="${#httpServletRequest.getContextPath()+'/static/x-admin/css/xadmin.css'}"/>
    <script type="text/javascript" th:src="${#httpServletRequest.getContextPath()+'/static/js/jquery.min.js'}"></script>



补充:通过JS获取request和session中变量的方法如下: 

第一种方法:



<script th:inline="javascript">     
        var currentUsername= /*[[${session.user.username}]]*/;      
        var address=/*[[${message.address}]]*/    
    </script>



 

第二种方法:



<script th:inline="javascript">     
        /*<![CDATA[*/
            var currentUsername= /*[[${session.user.username}]]*/;      
           /*]]>*/
    </script>



 

 

4.    thymeleaf 获取session中的值

后台存:



@RequestMapping("doLogin")
    @ResponseBody
    public JSONResultUtil doLogin(String username, String password, HttpSession session) {
        User loginUser = null;
        if (username.equals("admin") && password.equals("admin")) {
            loginUser = new User();
            loginUser.setFullname("系统管理员");
        } else {
            loginUser = userService.getUserByUserNameAndPassword(username, password);
        }

        if (loginUser == null) {
            return JSONResultUtil.error("账号或者密码错误");
        }

        session.setAttribute("user", loginUser);
        return JSONResultUtil.ok();
    }



前台:



<span class="x-red" th:text="${session.user.fullname}">admin</span>



 

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

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

      https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html

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

 

0.字符串拼接



<a th:href="${context+'/JS/XXXX'+context}">XXX</a>



   context是变量,单引号中间的是常量

结果:

freemarker下标获取_freemarker下标获取_10

 

1.基本使用方式

标签如果取到属性就会取代原来界面上的对应的属性。

例如对于如下页面:



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



(1)查看静态页面

freemarker下标获取_freemarker下标获取_11

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

 

freemarker下标获取_ViewUI_12

 

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')}"/>



 界面查看:

freemarker下标获取_后端_13

 

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>



结果:

freemarker下标获取_ViewUI_14

 

5.URL

  URL的用法是: @{url}。

例如:



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



结果:

freemarker下标获取_javascript_15

 

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

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



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



对应的目录结构:

freemarker下标获取_java_16

页面引入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查看结果页面填充结果:

freemarker下标获取_后端_17

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";
    }



前台填充后结果:

freemarker下标获取_javascript_18

 

例如:循环取list中数据放入option



<select name="bodylocation" >
                      <option th:each="body:${bodys}" th:text="${body}" th:value="${body}"></option>
                  </select>



循环中option的选中回显如下:



<select name="bodylocation" >
                      <option th:each="body:${bodys}" th:text="${body}" th:value="${body}" th:selected="${plan.bodylocation eq body}"></option>
                  </select>



补充:循环遍历Map中数据 



<input type="text" name="foods" autocomplete="off" class="layui-input"
                      th:each="entry:${foods}" th:placeholder="${entry.key}" th:class="entry.value" οnchange=""/>



补充:遍历List<Map>的方式,已经知道Map中的key



<tr th:each="sequence:${sequences}">
                <td th:text="${sequenceStat.index+1}"></td>
                <td th:utext="${sequence['fullname']}"></td>
                <td th:text="${sequence['stepnumber']}"></td>
            </tr>



 

补充:遍历出来也有一个状态信息,可以获取序号、是否第一个等信息,如下:

When using th:each, Thymeleaf offers a mechanism useful for keeping track of the status of your iteration: the status variable.

Status variables are defined within a th:each attribute and contain the following data:
• The current iteration index, starting with 0. This is the index property.
• The current iteration index, starting with 1. This is the count property.
• The total amount of elements in the iterated variable. This is the size property.
• The iter variable for each iteration. This is the current property.
• Whether the current iteration is even or odd. These are the even/odd boolean properties.
• Whether the current iteration is the first one. This is the first boolean property.
• Whether the current iteration is the last one. This is the last boolean property.

例如:



<tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
    <td th:text="${prod.name}">Onions</td>
    <td th:text="${prod.price}">2.41</td>
    <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
  </tr>


 

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)建立相应文件:

freemarker下标获取_ViewUI_19

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>



查看填充后的源码:

freemarker下标获取_javascript_20

 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";
    }



前台填充后结果:

freemarker下标获取_ViewUI_21

 

13 .  判断集合不为空集合



<div th:unless="${#lists.isEmpty(commentsByViewId)}">
            <b>评论:<br/></b>
            <div th:each="comment:${commentsByViewId}">
                <span th:text="${#dates.format(view.createtime, 'yyyy-MM-dd')}"></span>
                <span th:text="${comment.content}"></span>
            </div>
        </div>