【发布时间】:2018-11-09 03:35:06
【问题描述】:
我使用 Thymeleaf 创建了一个由控制器监听的表单。当我输入一个包含前导或尾随空格的字符串时(例如:“ abc “。),在控制器中自动修剪的字符串(例如:“abc”。)。但我想保留这些前导或尾随空格,即使是传递给控制器的值。我该怎么做?
示例代码:
使用 Thymeleaf 的表单:
<form role="form" action="/" method="post" autocomplete="off" th:action="@{/change-password}" th:object="${form}">
<div>
<label for="new-pass" th:text="#{password.newPassword}">New password</label>
<input type="password" th:field="*{password}" th:placeholder="#{password.newPassword}" required="required" />
</div>
<div>
<button type="submit" th:text="#{confirm}">Change</button>
<a href="/" th:href="@{/}" th:text="#{cancel}">Cancel</a>
</div>
</form>
页面控制器:
@RequestMapping(value = "/change-password", method = RequestMethod.GET)
public String changePassword(@ModelAttribute("form") ChangeMyPasswordForm form) {
return "/account/change-pass";
}
处理表单动作的控制器:
@RequestMapping(value = "/change-password", method = RequestMethod.POST)
public void changeSelfPassword(ChangeMyPasswordForm form) {
System.out.println(form.getPassword());
}
类 ChangeMyPasswordForm:
public class ChangeMyPasswordForm {
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
表单中输入的字符串:
" abc "
控制器 System.out.println 中的预期结果:
" abc "
实际结果:
"abc"
【问题讨论】:
标签: java spring spring-mvc thymeleaf