springboot默认不支持JSP,需要引入第三方模板引擎技术实现页面渲染
视图处理方式:转发,重定向,自定义视图
1:引入starter
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
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>Titletitle>
head>
<body>
<h1 th:text="${msg}" >哈哈h1>
<h2>
<a href="www.hello.com" th:href="${link}" >去百度1a>
<a href="www.hello.com" th:href="@{/link}" >去百度1a>
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);
}
}
因此如果我们想通过第二种写法实现跳转到百度页面,那么正确写法如下所示:
<a href="www.hello.com" th:href="@{/http://www.baidu.com}">去百度2a>
并且这两种写法还有一个区别就是如果我们给当前项目设置了上文访问路径,那么第二种写法会自动的将将其补上,如下所示:
我们设置了项目的访问路径为demo
server:
servlet:
context-path: /demo
通过重启项目后,检查页面源码如下所示: