当前位置: 代码迷 >> java >> spring:bind和JSR-303验证。 验证失败时,无法在页面上显示错误消息
  详细解决方案

spring:bind和JSR-303验证。 验证失败时,无法在页面上显示错误消息

热度:72   发布时间:2023-07-25 19:53:09.0

我需要协助。 我在做宠物项目时遇到麻烦。 这是一个基于spring mvc的简单Crud应用程序。 问题是当profile.jsp输入验证失败时,我不会收到错误消息。 我的signup.jsp代码基本上相同,但是一切正常。

有我的控制器方法:

@RequestMapping(value = "/profile", method = RequestMethod.GET)
    public String getUserProfile(Model model) {
        model.addAttribute("userDetailsForm", new UserDetailsFormDTO());
        model.addAttribute("passwordForm" ,new PasswordFormDTO());
        model.addAttribute("profile", getCurrentUser());
        return "profile";
    }

@RequestMapping(value = "/profile/details/change", method = RequestMethod.POST)
public String changeUserDetails(@ModelAttribute("userDetailsForm") @Valid UserDetailsFormDTO form,
        BindingResult result) {
    if(result.hasErrors()){
        result.getAllErrors().forEach(log::debug);
        return "redirect:/profile";
    }
    userService.changeUserDetails(getCurrentUser(), form);
    return "redirect:/profile?success=details";
}

我正在使用JSR 303验证:

package org.crud.dto;

import java.io.Serializable;

import javax.validation.constraints.Pattern;

import org.crud.validation.InputValidator;
import org.hibernate.validator.constraints.NotEmpty;

public class UserDetailsFormDTO implements Serializable{

    private static final long serialVersionUID = -7603395840362468805L;

    @NotEmpty(message="{error.null_form_value}")
    @Pattern(regexp=InputValidator.FIRSTNAME_PATTERN, message="{error.name_invalid}")
    private String firstName;

    @NotEmpty(message="{error.null_form_value}")
    @Pattern(regexp=InputValidator.LASTNAME_PATTERN, message="{error.name_invalid}")
    private String lastName;

    public UserDetailsFormDTO() {}

    public UserDetailsFormDTO(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

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

    public String getLastName() {
        return lastName;
    }

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

}

在配置文件中,我声明了下一个bean:

<bean id="validator"
        class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"
        p:validationMessageSource-ref="messageSource" />

<bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>

在类路径上也有两个带有我的标签和错误代码的.properties文件: messages_rumessages_en

我的profile.jsp代码片段:

<div id="user-details-upd" class="panel panel-info">
    <div class="panel-heading">
        <h3 class="panel-title">Update user details</h3>
    </div>
    <div class="panel-body">
        <div class="container-fluid">

            <form name="userDetailsForm" class="form-horizontal" role="form" method="POST" action="profile/details/change">
                <spring:bind path="userDetailsForm"></spring:bind>
                <div class="form-group">
                    <div class="row">
                        <label for="fname-input" class="col-md-offset-2 col-md-2 control-label">First name:</label>
                        <div class="col-md-5">
                            <spring:message code="label.fname_placeholder" var="fNameHolder" />
                            <spring:bind path="userDetailsForm.firstName">
                                <input type="text" value="${profile.getFirstName()}" name="<c:out value="${status.expression}"/>" class="form-control" placeholder="${fNameHolder}" required>
                                <c:if test="${status.error}">
                                    <c:forEach items="${status.errorMessages}" var="error">
                                        <small class="text-danger"> <c:out value="${error}" />
                                        </small>
                                    </c:forEach>
                                </c:if>
                            </spring:bind>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <div class="row">
                        <label for="lname-input" class="col-md-offset-2 col-md-2 control-label">Last name:</label>
                        <div class="col-md-5">
                            <spring:message code="label.lname_placeholder" var="lNameHolder" />
                            <spring:bind path="userDetailsForm.lastName">
                                <input type="text" value="${profile.getLastName()}" name="<c:out value="${status.expression}"/>" class="form-control" placeholder="${lNameHolder}" required>
                                <c:if test="${status.error}">
                                    <c:forEach items="${status.errorMessages}" var="error">
                                        <small class="text-danger"> <c:out value="${error}" />
                                        </small>
                                    </c:forEach>
                                </c:if>
                            </spring:bind>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <div class="row">
                        <div class="col-md-offset-4 col-md-5">
                            <button type="submit" value="Submit" class="btn btn-success">
                                <span class="glyphicon glyphicon-edit" aria-hidden="true"></span> Update
                            </button>
                        </div>
                    </div>
                </div>

            </form>
        </div>
    </div>
</div>

当我在lastName输入中提交不正确的数据时,来自调试的消息:

2015-08-07 18:52:29 DEBUG UserController:? - Field error in object 'userDetailsForm' on field 'lastName': rejected value [jh]; codes [Pattern.userDetailsForm.lastName,Pattern.lastName,Pattern.java.lang.String,Pattern]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [userDetailsForm.lastName,lastName]; arguments []; default message [lastName],[Ljavax.validation.constraints.Pattern$Flag;@657f42ee,([A-Z?-?][a-zA-Z?-?]*)([\s\'-][A-Z?-?][a-z?-?]*)*]; default message [Name must contain only characters and first letter must be in uppercase]

我不明白,为什么status.errorMessages出错时status.errorMessages为空?

任何帮助或建议,表示赞赏。 提前致谢

您正在控制器的请求映射块内使用重定向。 重定向是发送到浏览器的标头。 浏览器启动重定向,因此您从浏览器收到一个全新的请求,并且由于http是无状态的,因此您丢失了存储在该先前请求/响应中的任何内容,例如BindingResult。

删除重定向,并使用字符串转发到jsp页面。 您可以为此使用internalviewresolver

  相关解决方案