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

时间:2018-11-09 03:35:07

标签: java spring spring-mvc thymeleaf

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

1 个答案:

答案 0 :(得分:1)

首先,您需要检查百里香或Spring在哪里截断了这些值?

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

默认情况下,弹簧不会修剪参数。只需使用StringTrimmerEditor来检查您是否,如下所示。

@Controller
public class MyFormController {

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

    // ...
}