Motor de plantillas
SpringBoot recomienda usar un motor de plantillas para renderizar html. Si no es un proyecto histórico, no debe usar JSP. Hay muchos motores de plantillas de uso común, como freemark, thymeleaf, etc., pero todos son iguales.
Entre ellos, springboot recomienda encarecidamente thymeleaf :
1) Agregue compatibilidad con thymeleaf para archivos pom y elimine la compatibilidad con JSP:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--<!–JavaServer Pages Standard Tag Library,JSP标准标签库–>-->
<!--<dependency>-->
<!--<groupId>javax.servlet</groupId>-->
<!--<artifactId>jstl</artifactId>-->
<!--</dependency>-->
<!--<!–内置tocat对Jsp支持的依赖,用于编译Jsp–>-->
<!--<dependency>-->
<!--<groupId>org.apache.tomcat.embed</groupId>-->
<!--<artifactId>tomcat-embed-jasper</artifactId>-->
<!--</dependency>-->
2) Elimine el contenido del analizador de vistas en el archivo application.properties:
~~#spring.mvc.view.prefix=/WEB-INF/jsp/
#spring.mvc.view.suffix=.jsp~~
3) El contenido del nuevo controlador es el siguiente
package cn.enjoy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/tpl")
public class ThymeleafController {
@RequestMapping("/testThymeleaf")
public String testThymeleaf(ModelMap map) {
// 设置属性
map.addAttribute("name", "enjoy");
// testThymeleaf:为模板文件的名称
// 对应src/main/resources/templates/testThymeleaf.html
return "testThymeleaf";
}
}
4) La ruta de configuración de la plantilla predeterminada para Springboot es: src / main / resources / templates :
Cree un nuevo directorio de plantillas en el directorio de recursos y cree un nuevo archivo testThymeleaf.html en el directorio:
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head lang="en">
<meta charset="UTF-8" />
<title>enjoy</title>
</head>
<body>
<h1 th:text="${name}"/>
</body>
</html>
在浏览器上输入:localhost:8080/tpl/testThymeleaf,可以看到页面。
Capítulo anterior: Introducción simple a springboot (5-1): Integración de interfaz front-end-Jsp