Spring Boot中如何从URL取参数并在HTML页面显示?
问题原因
静态HTML文件无法解析EL表达式(${name}),因为这类表达式是JSP、Thymeleaf等模板引擎的专属语法,纯静态HTML只会将${name}作为普通文本原样输出。
解决方案
以下是三种可行的实现方式,根据你的需求选择即可:
方案一:使用Thymeleaf模板引擎(Spring Boot官方推荐)
Thymeleaf是Spring Boot默认集成的模板引擎,能轻松渲染动态数据到页面。
- 确保依赖正确
如果使用Maven,检查pom.xml中是否包含Thymeleaf依赖(Spring Boot Starter Web通常已内置,若缺失则手动添加):
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
- 调整HTML文件
将HTML文件移至src/main/resources/templates目录(Thymeleaf默认模板路径),并在<html>标签添加Thymeleaf命名空间,使用th:text属性渲染动态内容:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Welcome Page</title> </head> <body> <!-- 两种字符串拼接写法任选其一 --> <h1 th:text="'Welcome ' + ${name}">Welcome Guest</h1> <!-- <h1 th:text="|Welcome ${name}|">Welcome Guest</h1> --> </body> </html>
- 优化Controller代码(可选)
无需手动操作Session,直接通过Model传递参数更简洁,Spring MVC会自动绑定URL中的name参数:
package com.example.demo; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class IndexController { @RequestMapping("index") public String index(Model model, String name) { if (name != null) { System.out.println("Hi! " + name); } else { System.out.println("Hi"); } model.addAttribute("name", name); return "index"; } }
方案二:改用JSP
若习惯JSP语法,可调整Spring Boot配置支持JSP:
- 添加JSP依赖
<dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency>
- 配置视图解析器
在application.properties中添加:
spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp
- 创建JSP文件
在src/main/webapp/WEB-INF/jsp目录下新建index.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Welcome</title> </head> <body> <h1>Welcome ${name}</h1> </body> </html>
方案三:纯HTML+JavaScript前端解析
如果不想使用后端模板引擎,可通过JS直接从URL中提取参数并渲染:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Welcome</title> <script> window.onload = () => { const urlParams = new URLSearchParams(window.location.search); const name = urlParams.get('name'); const welcomeText = name ? `Welcome ${name}` : 'Welcome Guest'; document.getElementById('welcome').textContent = welcomeText; } </script> </head> <body> <h1 id="welcome">Welcome Guest</h1> </body> </html>
内容的提问来源于stack exchange,提问作者Debendra Nath Mukherjee
相关产品推荐
相关产品推荐

