Spring Boot基础 - Web应用 - 02

xiaoxiao2021-02-28  6

Spring Boot为我们集成了不同的模板引擎,对以下的视图模板都进行了支持

ThymeleafFreemarkerVelocity

本文以thymeleaf进行演示,就是html文件


1.在pom文件中添加对thymeleaf的引用

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>

2.编写controller层 注意controller层要在application.java[就是带有main方法的那个文件]包同级或者下级,否则可能会出席扫描不到等异常

import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class IndexController { @RequestMapping("/") public String index(ModelMap map) { // 加入一个属性,用来在模板中读取 map.addAttribute("name", "Hello Spring Boot!!"); // return模板文件的名称,对应路径为src/main/resources/templates/index.html return "index"; } }

3.在src/main/resources/templates/目录下创建index.html

<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8" /> <title>test</title> </head> <body> <h1 th:text="${name}">Hello World</h1> test </body> </html>

大功告成!!

至于json返回的话,与以前的spring Mvc并无太大区,但是新增一个注解@RestController 是@controller和@ResponseBody和结合,用于类上面,表示是controller层,并且所有返回的数据会以json返回

转载请注明原文地址: https://www.6miu.com/read-1100295.html

最新回复(0)