视图解析:
springboot默认不支持JSP,需要引入第三方模板引擎技术实现页面渲染
视图处理方式:转发,重定向,自定义视图
thymeleaf的使用:
1:引入starter
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
2:自动配置好了Thymeleaf,查看ThymeleafAutoConfiguration
源码如下所示:
@AutoConfiguration( after = {WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class} ) @EnableConfigurationProperties({ThymeleafProperties.class}) @ConditionalOnClass({TemplateMode.class, SpringTemplateEngine.class}) @Import({TemplateEngineConfigurations.ReactiveTemplateEngineConfiguration.class, TemplateEngineConfigurations.DefaultTemplateEngineConfiguration.class}) public class ThymeleafAutoConfiguration {
自动装配的策略:
1:所有thymeleaf的配置值都在ThymeleafProperties
2:配置好了SpringTemplateEngine
3:配置好了ThymeleafViewResolver
public static final String DEFAULT_PREFIX = "classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html";
开发:
package com.example.demo.Controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class ViewControllerTest { @GetMapping("/hello") public String show(Model model){ model.addAttribute("msg","你好,springboot"); model.addAttribute("link","http://www.baidu.com"); return "success"; } }
必须在html页面中引入thymeleaf取值空间xmlns:th="http://www.thymeleaf.org
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1 th:text="${msg}" >哈哈</h1> <h2> <!--它是一个服务器端的变量表达式,需要在服务器端进行解析和替换,所以需要使用Thymeleaf来解析。这种方式可以实现动态跳转,因为${link}可以在服务器端根据条件动态生成不同的URL --> <a href="www.hello.com" th:href="${link}" >去百度1</a> <!--它是Thymeleaf的URL语法,会根据应用程序的上下文自动解析和替换URL。这种方式适用于在模板文件中直接写死跳转的URL,不能实现动态跳转 --> <a href="www.hello.com" th:href="@{/link}" >去百度1</a> </h2> </body> </html>
springboot启动项目:
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Demo3Application { public static void main(String[] args) { SpringApplication.run(Demo3Application.class, args); } }