Spring Boot 集成 Thymeleaf (二)

 上一篇文件我们通过一个实例进行了spring boot入门,学会了简单的入门案例

接下来我们来了解一下怎么实现Spring Boot 集成 Thymeleaf。

1.创建springboot项目

和之前的spring boot入门案例的创建过程只有下面一点点的不同,不会的请参考我的第一篇spring boot文章!

Spring Boot 集成 Thymeleaf (二)_第1张图片

2.添加Maven依赖




    org.springframework.boot

    spring-boot-starter-thymeleaf

3. 改造html代码

原来的login.html





    
    Title


   
       

请 登 录

                           

现在的login.html



  

  

    

    Title

  

  

  
   
       

请 登 录

                           

 

1.2.1 xmlns:th命名空间

使用Thymeleaf引擎需要在html标签添加Thymeleaf模板引擎的命名空间:xmlns:th=”http://www.thymeleaf.org”,这样的话才可以在其他标签里面使用th:*这样的语法.这是下面语法的前提。

 

1.2.2 th:href=”@{…}”的使用

引用的绝对路径也可以用模板改造,“@{}”为引用静态资源文件,如:



可以用thymeleaf模板改写为@{}的形式表示



会引入/static目录下的/css/下的文件;

1.2.3 th:action=”@{…}”的使用

表单POST的action url也可以用@{}表示:如

现在

测试一下

创建controller

package com.liuyongqi.springbootthymeleaf.conrtoller;

  

  import org.springframework.stereotype.Controller;

  import org.springframework.web.bind.annotation.RequestMapping;

  import org.springframework.web.bind.annotation.RequestMethod;

  

  /**

 * @ClassName: LoginController

 * @Description: TODO

 * @Author: Administrator

 * @CreateDate: 2018/11/7 21:02

 * @UpdateUser: Administrator

 * @UpdateDate: 2018/11/7 21:02

 * @UpdateRemark: 修改内容

 * @Version: 1.0

 */

  @Controller

  public class LoginController {

    @RequestMapping(value = "/",method = RequestMethod.GET)

    public String home(){

        System.out.println("home");

        return "login";

    }

}

运行一下,结果正常 

Spring Boot 集成 Thymeleaf (二)_第2张图片

1.2.4 th:object=”${…}”th:field=”*{…}”的使用

...用于获取变量值,对于javaBean的话使用变量名.属性名,如...用于获取变量值,对于javaBean的话使用变量名.属性名,如{user.name}

举个例子,如若需要将后台的值回显到前台,那应该怎么做,此时th:object=”${…}”与th:field=”*{…}”就派上用场了。

   

请 登 录

           

在表单代码中增加th:object属性,将name属性换成th:field属性,其中th:object定义表单数据提交对象user,th:field定义表单数据属性,*{}锁定上级定义的对象,{}内填写对象属性,提交表单时自动将属性值注入到对象中。 

@RequestMapping(value = "/setValue",method = RequestMethod.GET)

  public String setValue(Model model, Users users){

    model.addAttribute("users",users);

    return "login";

}

  @RequestMapping(value = "/login",method = RequestMethod.POST)

  public String login(Model model, Users users){

    System.out.println("login");

    System.out.println("POJO: " + users.getClass().getName() +

            ", hash code: " + users.hashCode() + ", " + users.toString());

    model.addAttribute("users",users);

    return "success";

}

我们来运行一下,输入http://localhost:8080/springbootthymeleaf/setValue?username=admin&password=888888得到如下界面: 

Spring Boot 集成 Thymeleaf (二)_第3张图片

输入用户名admins及密码123456,点击登录,得到如下结果 

Spring Boot 集成 Thymeleaf (二)_第4张图片

最后建议在application.properties配置关闭thymeleaf缓存,因为Spring Boot使用thymeleaf时默认是有缓存的,即你把一个页面代码改了不会刷新页面的效果,你必须重新运行spring-boot的main()方法才能看到页面更改的效果。

spring.thymeleaf.cache: false

今天就写到这里了,谢谢大家支持!

如果大家想浏览我的下一篇文章,请留言

版权声明:此文章属于原创,不准随意转载:https://blog.csdn.net/LYQ2332826438

 

你可能感兴趣的:(java,文档,Spring,Boot)