如何将localStorage中的值传递给Spring Boot的@PostMapping处理器?
解决Spring Boot中传递localStorage值到@PostMapping的问题
为什么你的原有方法无效
${userLogin}是Thymeleaf在服务端渲染页面时生成的静态内容,当浏览器加载页面执行JS时,这个表达式已经被替换成具体文本(或空值),前端JS无法直接修改这个服务端变量来让后端接收到值。
解决方案1:使用隐藏表单字段
这是最直接的方式,通过在表单中添加隐藏input,用JS将localStorage的值赋值给该字段,提交表单时自动传递给后端。
HTML代码
<form th:action="@{/inbox}" method="post" th:object="${formData}"> <!-- 你的其他表单字段,对应formData的属性 --> <input type="text" th:field="*{message}" placeholder="输入消息"> <!-- 新增隐藏字段,用于传递userLogin --> <input type="hidden" name="userLogin" id="userLoginHidden"> <button type="submit">发送消息</button> </form> <script> // 页面加载完成后,从localStorage取值并赋值给隐藏字段 window.onload = function() { const senderName = localStorage.getItem('senderName'); if (senderName) { document.getElementById('userLoginHidden').value = senderName; } }; </script>
后端代码调整(可选)
你可以保持原有代码不变,也可以将@ModelAttribute("userLogin")替换为@RequestParam("userLogin"),逻辑更直观:
@PostMapping("/inbox") public String doCreateMessage( @ModelAttribute("formData") CreateMessageFromData formData, @RequestParam("userLogin") String userLogin, Model model ) { Message message = new Message(formData.getId(), formData.getMessage(), userLogin); messageRepository.save(message); return "redirect:/inbox"; }
解决方案2:AJAX提交表单
如果不想刷新页面,可以用AJAX提交,手动将localStorage的值加入请求参数:
<form id="messageForm" th:action="@{/inbox}" method="post" th:object="${formData}"> <input type="text" th:field="*{message}" placeholder="输入消息"> <button type="submit">发送消息</button> </form> <script> document.getElementById('messageForm').addEventListener('submit', function(e) { e.preventDefault(); // 阻止默认表单提交 const formData = new FormData(this); const senderName = localStorage.getItem('senderName'); if (senderName) { formData.append('userLogin', senderName); // 将localStorage的值加入表单数据 } // 发送POST请求 fetch(this.action, { method: 'POST', body: formData }).then(response => { if (response.ok) { window.location.href = '/inbox'; // 提交成功后跳转 } }).catch(error => { console.error('提交失败:', error); }); }); </script>
注意事项
- 要处理localStorage中
senderName为null的情况,避免传递空值到后端。 - 如果
userLogin是敏感信息,不建议存在localStorage(易被XSS攻击窃取),建议改用服务端Session存储。
内容的提问来源于stack exchange,提问作者Chrone Void
相关产品推荐
相关产品推荐

