gpt4 book ai didi

java - 在 Spring 中使用 Thymeleaf 获取表单数据时如何禁用空白修剪

转载 作者:行者123 更新时间:2023-12-02 10:36:57 24 4
gpt4 key购买 nike

我使用 Thymeleaf 创建了一个由 Controller 监听的表单。当我输入包含前导空格或尾随空格的字符串时(例如:“abc ".), Controller 中自动修剪的字符串(例如:"abc"。)。但我想保留这些前导或尾随空格,甚至是传递到 Controller 的值。我该怎么做?

示例代码:

使用 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>

页面 Controller :

@RequestMapping(value = "/change-password", method = RequestMethod.GET)
public String changePassword(@ModelAttribute("form") ChangeMyPasswordForm form) {
return "/account/change-pass";
}

处理表单操作的 Controller :

@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   "

Controller System.out.println 中的预期结果:

"   abc   "

实际结果:

"abc"

最佳答案

首先,您需要检查值在 thymeleaf 或 Spring 中被截断的位置?

您可以通过在提交表单之前使用 jquery/javascript 打印值来实现这一点。

默认情况下 spring 不会修剪参数。只需检查您是否使用 StringTrimmerEditor像下面这样。

@Controller
public class MyFormController {

@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}

// ...
}

关于java - 在 Spring 中使用 Thymeleaf 获取表单数据时如何禁用空白修剪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53219486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com