1. 程式人生 > >第十八章 springboot + thymeleaf

第十八章 springboot + thymeleaf

doctype 5-0 ide sed sheet ram 代碼結構 web 默認

代碼結構:

技術分享

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; } }
View Code

說明:

  • 第一個是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>
View Code

說明:

  • 引入外界靜態資源的方式@{/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