springboot整合thymeleaf

1、引用maven包

<!-- ThymeLeaf 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

2、配置文件

  ###ThymeLeaf配置
spring: 
  thymeleaf:
      #模板的模式,支持 HTML, XML TEXT JAVASCRIPT
      mode: HTML5
      #编码 可不用配置
      encoding: UTF-8
      #内容类别,可不用配置
      content-type: text/html
      #开发配置为false,避免修改模板还要重启服务器
      cache: false
      #配置模板路径,默认是templates,可以不用配置
      prefix: classpath:/templates/

3、创建静态目录templates

4、test.html代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
</head>
<script src="./js/jquery-3.4.1.min.js"></script>
<body>
<button type="button" onclick="test()">提交</button>
<div id="message"></div>
</body>

<script>
    function test(){
        $.ajax({
            type : "GET",
            dataType: "json",  //通过GET方式上传请求,如果接口返回的数据类型为string,这里要改为"text"
            // data : data,                                 //上传的参数
            async: false ,
            url : "http://localhost:8061/api/test",     //请求的url。与后端@Request Mapping注解中的值一致。
            success: function(result) {
                debugger;
                console.log(result);//请求成功的回调函数
                $("#message").html(result.key1);
            }
        });
    };
</script>
</html>

5、thymeleaf是通过view model的原理跳转的,必须有个controller做为跳转路径:localhost:8081/test

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class ViewController {

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String test(){

        return "test";
    }
}

6、test.html中ajax调用的json数据的接口controller

@RestController
@RequestMapping("/api")
public class TestController {



    @GetMapping("/test")
    public Map<String,String> start(){
        Map<String,String> map =new HashMap<>();
        map.put("key1","value1");
        return map;
    };

   

}

至此完毕,注意点:viewcontroller的返回数据类型必须是string

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值