首页 > 代码库 > 第十八章 springboot + thymeleaf
第十八章 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 = "http://www.mamicode.com/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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。