首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在Spring中从服务器端呈现Html/js

在Spring中,可以使用模板引擎(如Thymeleaf、Freemarker、Velocity等)从服务器端呈现HTML/JS,或者使用Spring MVC的Controller来返回视图名称,然后由视图解析器解析并返回相应的HTML文件。

以下是使用Thymeleaf模板引擎从服务器端呈现HTML/JS的步骤:

1. 添加依赖

pom.xml文件中添加Thymeleaf依赖:

代码语言:javascript
复制
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2. 配置Thymeleaf

application.propertiesapplication.yml文件中配置Thymeleaf:

代码语言:javascript
复制
# application.properties
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false

3. 创建Controller

创建一个Spring MVC Controller来处理请求并返回Thymeleaf模板名称:

代码语言:javascript
复制
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";
    }
}

4. 创建Thymeleaf模板

src/main/resources/templates目录下创建一个名为hello.html的Thymeleaf模板文件:

代码语言:javascript
复制
<!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>

5. 运行应用程序

启动Spring Boot应用程序,并访问http://localhost:8080/hello,你将看到渲染后的HTML页面,并且在控制台中看到JavaScript输出的日志。

使用Spring MVC的Controller返回视图名称

如果你不想使用模板引擎,可以直接使用Spring MVC的Controller来返回视图名称,然后由视图解析器解析并返回相应的HTML文件。

代码语言:javascript
复制
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模板引擎可以更方便地处理动态内容,并且可以轻松地将数据传递给前端。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

5分57秒

JSP视频教程-01_JSP规范介绍

33分11秒

JSP视频教程-03_JSP文件Java命令书写规则

15分35秒

JSP视频教程-05_Servlet与JSP文件分工

22分21秒

JSP视频教程-07_Servlet与JSP实现_试题添加功能

8分30秒

JSP视频教程-09_Servlet与JSP实现_试题更新功能

6分54秒

EL表达式-03_EL表达式初始

18分19秒

EL表达式-05_将引用对象属性内容写入到响应体

15分51秒

EL表达式_07_支持运算表达式

13分5秒

EL表达式_09_应用

34分6秒

考试管理系统_11_自动出题

39分57秒

EL表达式-13_模拟面试

10分9秒

JSP视频教程-02_JSP文件使用展示

领券