在Spring中,可以使用模板引擎(如Thymeleaf、Freemarker、Velocity等)从服务器端呈现HTML/JS,或者使用Spring MVC的Controller来返回视图名称,然后由视图解析器解析并返回相应的HTML文件。
以下是使用Thymeleaf模板引擎从服务器端呈现HTML/JS的步骤:
在pom.xml
文件中添加Thymeleaf依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在application.properties
或application.yml
文件中配置Thymeleaf:
# application.properties
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
创建一个Spring MVC Controller来处理请求并返回Thymeleaf模板名称:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class MyController {
@GetMapping("/hello")
public String hello(Model model) {
model.addAttribute("message", "Hello, Thymeleaf!");
return "hello";
}
}
在src/main/resources/templates
目录下创建一个名为hello.html
的Thymeleaf模板文件:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<h1 th:text="${message}"></h1>
<script th:inline="javascript">
/*<![CDATA[*/
console.log([[${message}]]);
/*]]>*/
</script>
</body>
</html>
启动Spring Boot应用程序,并访问http://localhost:8080/hello
,你将看到渲染后的HTML页面,并且在控制台中看到JavaScript输出的日志。
如果你不想使用模板引擎,可以直接使用Spring MVC的Controller来返回视图名称,然后由视图解析器解析并返回相应的HTML文件。
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class MyController {
@GetMapping("/hello")
public String hello() {
return "hello";
}
}
在这种情况下,你需要在src/main/resources/templates
目录下创建一个名为hello.html
的HTML文件,并确保视图解析器配置正确。
通过上述步骤,你可以在Spring中从服务器端呈现HTML/JS。使用Thymeleaf模板引擎可以更方便地处理动态内容,并且可以轻松地将数据传递给前端。
领取专属 10元无门槛券
手把手带您无忧上云