【问题标题】:Hibernate @Size Validator休眠 @Size 验证器
【发布时间】:2012-11-09 16:42:27
【问题描述】:

我有一个带有名字字段的表单的 spring mvc 应用程序。此字段应至少包含 3 个或更多字符。我在支持 bean 类中使用 hibernate @Size 验证器,如下所示:

@Size(min=3, message="message.key")
String firstName;

当此验证失败时,会显示相应的错误消息。但是,当页面在失败后重新加载时,输入的名字值会从输入字段中清除。如何使该值保留在字段中进行编辑?如果可能的话……

代码如下:

JSP 片段 - 这不是 portlet 应用程序

<portlet:renderURL var="createUserAction">
    <portlet:param name="action" value="createUser"/>
</portlet:renderURL>
<form:form method="post" commandName="userInformation" action="${createUserAction}" htmlEscape="false">
<h2>
    <fmt:message key="msg.label.form.title" bundle="${msg}" />
</h2>
<form:errors path="*" cssClass="errorblock" element="div"></form:errors>
<p>
    <form:label path="firstName">
        <fmt:message key="msg.label.form.fname" bundle="${msg}"/>
    </form:label>
   <form:input path="firstName" />
</p>
<p>
    <form:label path="lastName">
        <fmt:message key="msg.label.form.lname" bundle="${msg}"/>
    </form:label>
    <form:input path="lastName" />
</p>
<div style="margin-left: 150px; margin-top: 20px">
    <input type="submit" value="Save" /> 
    <input type="reset" value="Reset" />
</div>
</form:form>

豆子

@Component
public class UserInformation {


  @NotEmpty(message="msg.error.required.lname")
  private String lastName;

  @NotEmpty(message="msg.error.required.fname")
  @Size(min=3, message="msg.error.length.fname")
  private String firstName;

  public UserInformation() {
    super();
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

}

控制器

@Controller
@RequestMapping("VIEW")
public class UserManagement {

  @Autowired
  private UserInformation userInformation;

  @Autowired
  private Validator validator;

  @Autowired
  private MessageSource messageSource;

  @RequestMapping(params="page=addUser")
  public String addUser(Model model){
    userInformation = new UserInformation();
    model.addAttribute("userInformation", userInformation); 
    return Page.ADD_USER;
  }

  @RequestMapping(params="action=createUser")
  public String createUser(
   @ModelAttribute(value="userInformation") UserInformation userInformation,
   BindingResult result, Model model) throws ApplicationException{

    // get values
    String firstName = userInformation.getFirstName();

    System.out.println("fname="+firstName);

    Set<ConstraintViolation<UserInformation>> constraintViolations = 
     validator.validate(userInformation);

   for(ConstraintViolation<UserInformation> constraintViolation : constraintViolations) {
     String propertyPath = constraintViolation.getPropertyPath().toString();
     String message = constraintViolation.getMessage();
     result.addError(
       new FieldError(
         "member", 
         propertyPath, 
         messageSource.getMessage(
           message, 
           null, 
           Locale.ENGLISH
         )
       )
     );
  }
  // Errors found
  if(result.hasErrors()){
    return UMConstants.Page.ADD_USER;
  }

  String successMsg = messageSource.getMessage(
    "msg.user.added", 
    new Object[]{userInformation.getFirstName()}, 
    Locale.ENGLISH
   );

   model.addAttribute("successMsg", successMsg);

   return UMConstants.Page.INDEX;
  }
}

用户将单击执行 addUser 方法的链接以加载带有表单的页面,如上面的 JSP sn-p 所示。当用户点击提交按钮时,createUser 方法被调用。这是完成验证的地方。

【问题讨论】:

  • 从request中获取值并再次将值设置为request。
  • 谢谢。你能给我举个例子吗?我要将值打印到日志中,但我不确定如何将值设置为请求。
  • 您可以添加您所引用的代码

标签: java hibernate validation


【解决方案1】:

我遇到了同样的问题,我通过(痛苦地)迭代 Spring MVC form:input jsp 标记的源代码找到了解决方案......我想我会在这里分享它,也许它可以帮助某人。

简而言之:问题来自form:input 标签。此标记在评估其值时检查与此字段相关的错误(path 属性),如果发现任何错误,它将使用FieldError 实例的rejectedValue 属性而不是字段的值从命令或表单对象。

在控制器方法的参数中使用@Valid 注解时,Spring 将正确填充FieldError 对象上的rejectedValue 属性。

但是,如果您使用短构造函数(3 个参数)手动创建 FieldError 对象,则不会设置 FieldErrorrejectedValue 属性,并且标签将使用此 null 值进行显示...

解决方案是在创建FieldError 对象时使用构造函数的长版本,例如:

result.addError(
       new FieldError(
         "member", 
         "firstName", 
         userInformation.getFirstName(),
         false,
         new String[0],
         new Object[0],
         messageSource.getMessage(
           message, 
           null, 
           Locale.ENGLISH
         )
       )
     );

form:input 标记将使用FieldErrorrejectedValue 属性,这是这个更长的构造函数中的第三个参数,并且在使用更简单的 3 args 构造函数时没有设置...

请注意,命令或表单对象(此处为 userInformation)上的实际值始终是正确的,这使得该错误/怪癖很难跟踪。

希望最终对某人有所帮助...

【讨论】:

    【解决方案2】:

    在返回前发生错误时尝试将用户信息添加到模型中

    if(result.hasErrors()){
    model.addAttribute("userInformation", userInformation); 
    return UMConstants.Page.ADD_USER;
    

    }

    更新

    我想我发现了你的问题。当您遇到错误时,您调用 addUser 方法并在 add user 方法中创建新的 UserInformation 对象,并且该对象没有要在页面上显示的值。您可以在 addUser 方法中尝试以下类似的方法。

    @RequestMapping(params="page=addUser")
    public String addUser(Model model,HttpServletRequest request){
        userInformation =  (UserInformation)request.getAttribute("userInformation");
    
       if(userInformation == null){
        userInformation = new UserInformation();
       }
        model.addAttribute("userInformation", userInformation); 
        return Page.ADD_USER;
      }
    

    【讨论】:

    • 在方法签名中使用 ModelMap 而不是 Model。
    • 等等,不是&lt;form:input&gt;标签的有效属性。
    • oh oki 忽略它并尝试在 jsp 中的某个位置打印 ${firstName} 看看你是否能看到你的名字。
    • 我没有添加请求参数,保持代码与您最初的答案相似。我所做的只是将&lt;c:out value="${userInformation.firstName}"&gt; 添加到JSP 文件中,验证失败后会在页面上打印出firstName 值。但是,它仍然没有按要求在文本字段中。
    • 我想我发现了你的问题。当您遇到错误时,您调用 addUser 方法并在 add user 方法中创建新的 UserInformation 对象,并且该对象没有要在页面上显示的值。您可以尝试在 addUser 方法中更新代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多