带有禁用输入的 Spring 模型绑定(bind)

标签 spring thymeleaf materialize

对不起一个愚蠢的问题,但我不太明白会发生什么,如果这是我怀疑的......好吧,我真的很茫然。
我正在使用 spring boot + thymeleaf + materialize css 来显示和验证表单。
现在,在我看到的许多示例中,我没有遇到的是这种情况:

一些表单域是预填充的,对客户来说应该是禁用的,显示它们的预填充值。这个预填充发生在 Controller 中,而我处理一些其他请求,并重定向到这个 View

我正在使用这样的 th:object 将 pojo 绑定(bind)到表单

<form id="register_form" action="#" th:action="@{/showform}" th:object="${userInfo}" method="post">
 <div class="input-field">
   <label th:text="#{label.surname}" for="surname"></label>
   <input type="text" th:field="*{surname}" id="surname" th:attr="value=${userInfo.surname}" />
 </div>
 <div class="input-field">
   <label th:text="#{label.name}" for="givenname"></label>
   <input type="text" th:field="*{givenname}" id="givenname" th:attr="value=${userInfo.givenname}" disabled="disabled" />
 </div></form>

并像这样在 Controller 的 POST 处理程序中获取它:
@RequestMapping(value = {"/showform"}, method = RequestMethod.POST)
public ModelAndView submitFormPage(@ModelAttribute("userInfo") @Valid UserInfo userInfo, 
      BindingResult bindingResult, RedirectAttributes redir) 
{      
  ModelAndView mview = new ModelAndView();

  if (bindingResult.hasErrors()) 
  {
     // show form again with error messages
     mview.addObject("userInfo", userInfo);
     mview.setViewName("/showform");
  }
  else 
  {
     // ...
  }

  return mview;
}

RedirectAttributes 的存在是出于其他一些原因。如您所见,表单上有两个元素,第一个启用,第二个禁用。
它们的值使用来自 POJO 的预填充值正确填充,我通过 ModelMap 传递到 View 。我也可以在 GET 处理程序中跟踪它。

但是我从 View 中返回的 ModelMap 包含上述 POJO,其值为 NULL,而不是绑定(bind)到禁用控件的元素。我希望它们由 value 属性的内容填充,即使这些控件被禁用。启用的控件可以正常携带它们的值。

还是仅仅是禁用的控件根本不包含在回发中?如果是这种情况,你会建议我怎么做?一些人建议添加一个晦涩的 CSS 来“伪造”禁用控件的行为。还是我错过了一般接线中的某些内容?

我对可能的解决方法感到恐惧-但我一定做错了什么.. th:attr 是我尝试过的解决方法之一,但似乎没有奏效。我也尝试使用 th:id 和 th:disabled 但它也没有帮助。

最佳答案

这里有个误区我想想disabled的使用.

A readonly element is just not editable, but gets sent when the according form submits. a disabled element isn't editable and isn't sent on submit. Another difference is that readonly elements can be focused (and getting focused when "tabbing" through a form) while disabled elements can't.



More detailed comparison

所以要回答你的问题:你应该选择readonly如果你想将你的属性绑定(bind)到你的 pojo并且用户仍然无法编辑它们。

关于带有禁用输入的 Spring 模型绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51163627/

相关文章:

java - Spring Boot + HTML 5 视频流

html - 在 HTML 中将类别移至最右侧,将文章移至左侧

spring-mvc - Thymeleaf View 解析器和 SpringMVC 3 InternalResourceViewResolver 一起使用

javascript - 如何使用谷歌脚本从侧边栏(也是 HTML)调用模式对话框(带有 HTML 文件)

javascript - 为什么品牌标志在全页宽度时不与内容对齐?

java - spring boot 1.2.5 @Configuration @Autowired 注释为空?

java - ModelMapper:根据子类选择映射

html - 在另一个 div 中垂直居中一个按钮在它自己的 div 中

javascript - 如何在 Spring 中正确创建 JavaScript 日期数组?

spring - 启用 Spring Repositories cvc-complex-type.2.4.c :The matching wildcard is strict, 但找不到元素 jpa:repositories 的声明