如何让Thymeleaf生成foo+bar式URL编码链接或调整表单提交编码?
Thymeleaf生成foo+bar格式URL编码及表单提交格式统一方案
一、让Thymeleaf生成foo+bar格式的URL编码链接
Thymeleaf的@{…}语法默认遵循URI编码规范(空格转%20),而你需要的foo+bar是application/x-www-form-urlencoded格式的编码,可以通过以下方式实现:
1. 自定义Thymeleaf表达式工具类
通过自定义工具类调用URLEncoder.encode()(该方法默认将空格转为+),并注册到Thymeleaf模板引擎中,直接在模板中使用:
步骤1:编写自定义工具类
import java.net.URLEncoder; import java.nio.charset.StandardCharsets; public class CustomUrlEncoder { public String encode(String input) { if (input == null) { return ""; } return URLEncoder.encode(input, StandardCharsets.UTF_8); } }
步骤2:注册到Thymeleaf模板引擎
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.thymeleaf.spring6.SpringTemplateEngine; import org.thymeleaf.spring6.dialect.SpringStandardDialect; @Configuration public class ThymeleafCustomConfig { @Bean public SpringTemplateEngine springTemplateEngine() { SpringTemplateEngine engine = new SpringTemplateEngine(); SpringStandardDialect dialect = new SpringStandardDialect(); // 注册自定义工具类,模板中通过#urlEncoder调用 dialect.addExpressionObject("urlEncoder", new CustomUrlEncoder()); engine.setDialect(dialect); return engine; } }
步骤3:模板中使用
直接拼接编码后的参数,避免用@{…}包裹已编码的内容(否则+会被转义为%2B):
<a th:href="'/target/path?param=' + ${#urlEncoder.encode(data)}">统一格式链接</a>
2. 手动拼接路径(极简方案)
如果不想自定义工具类,也可以直接在模板中通过Thymeleaf的表达式调用URLEncoder:
<a th:href="'/target/path?param=' + ${T(java.net.URLEncoder).encode(data, 'UTF-8')}">链接</a>
二、让HTML表单以foo%20bar格式提交数据
浏览器默认对application/x-www-form-urlencoded格式的表单提交会将空格转为+,这是HTTP规范的行为,无法通过HTML属性直接修改,可通过以下方式实现:
用JavaScript拦截提交并手动编码
通过监听表单的submit事件,阻止默认提交行为,使用encodeURIComponent()(将空格转为%20)手动编码参数后提交:
<form id="customForm" action="/submit" method="get"> <input type="text" name="content" th:value="${formData}"> <button type="submit">提交</button> </form> <script> document.getElementById('customForm').addEventListener('submit', function(e) { e.preventDefault(); const form = this; const searchParams = new URLSearchParams(); // 遍历表单元素,用encodeURIComponent编码值 Array.from(form.elements).forEach(el => { if (el.name && el.value) { searchParams.append(el.name, encodeURIComponent(el.value)); } }); // GET请求直接跳转编码后的URL window.location.href = `${form.action}?${searchParams.toString()}`; // 如果是POST请求,用Fetch提交 // fetch(form.action, { // method: form.method, // headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, // body: searchParams // }); }); </script>
内容的提问来源于stack exchange,提问作者Garret Wilson
相关产品推荐
相关产品推荐

