第十八章 springboot + thymeleaf
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第十八章 springboot + thymeleaf相关的知识,希望对你有一定的参考价值。
代码结构:
1、ThymeleafController
package com.xxx.firstboot.web; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @Api("测试Thymeleaf和devtools") @Controller @RequestMapping("/thymeleaf") public class ThymeleafController { @ApiOperation("第一个thymeleaf程序") @RequestMapping(value = "/greeting", method = RequestMethod.GET) public String greeting(@RequestParam(name = "name", required = false, defaultValue = "world") String name, Model model) { model.addAttribute("xname", name); return "index"; } @ApiOperation("thymeleaf ajax") @ResponseBody @RequestMapping(value = "/ajax", method = RequestMethod.GET) public String ajax(@RequestParam("username") String username) { return username; } }
说明:
- 第一个是springMVC经典返回形式modelAndView
- 第二个是ajax返回形式
2、index.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>index</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link th:href="@{/bootstrap/css/bootstrap.min.css}" rel="stylesheet"/> <link th:href="@{/bootstrap/css/bootstrap-theme.min.css}" rel="stylesheet" /> </head> <body> <div class="panel panel-primary"> <div class="panel-heading">hello</div> <div class="panel-body" th:text="${xname}"></div> </div> <div class="panel panel-warning"> <div class="panel-heading">hello</div> <div id="usernamediv" class="panel-body"></div> </div> <script type="text/javascript" th:src="@{/js/jquery-1.11.1.js}"></script> <script type="text/javascript" th:src="@{/bootstrap/js/bootstrap.min.js}"></script> <script th:inline="javascript"> $(function(){ $.ajax({ url:"/thymeleaf/ajax", data:{ username:"xxx" }, type:"get", dataType:"text", success:function(text){ alert(text); $("#usernamediv").text(text); } }); }); </script> </body> </html>
说明:
- 引入外界静态资源的方式@{/xxx},默认的静态资源的根是"static"
- ajax的返回类型dataType要选好(一般就是"text"/"json")
- ajax的请求方法类型type要与controller相同,否则抛出405错误
文档:
- thymeleaf的其他配置查看:《springboot实战》、http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html
- bootstrap:http://www.bootcss.com/
以上是关于第十八章 springboot + thymeleaf的主要内容,如果未能解决你的问题,请参考以下文章