【问题标题】:How to disable trimming of whitespace when getting form data with using Thymeleaf in Spring在 Spring 中使用 Thymeleaf 获取表单数据时如何禁用空格修剪
【发布时间】: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


    【解决方案1】:

    首先您需要检查值在哪里被截断 thymeleaf 或 Spring?

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

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

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

    【讨论】:

    • 谢谢,确实有一个StringTrimmerEditor。我删除了那个 StringTrimmerEditor,现在不再截断。
    • 很高兴为您提供帮助。
    猜你喜欢
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 2017-03-18
    • 2018-05-30
    • 2016-02-29
    • 1970-01-01
    • 2012-05-23
    相关资源
    最近更新 更多