spring form validation BindingResult总是返回false

时间:2016-06-27 02:49:47

标签: java spring validation jsp spring-mvc

我正在使用spring form验证来验证我的表单输入字段。我遇到了BindingResult的问题,即使我的输入字段为null / empty,我仍然返回false.i管理所有导入和一切都看起来很好。但正如我所说,我的验证不起作用,需要帮助解决这个问题......

形式:

  <%@include file="././Header.jsp"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<script src="<c:url value="/js/smlibray/emailCommunicate.js"/>"></script>
 <link href="<c:url value="/js/jquery-ui.css"/>" rel="stylesheet" />
<script src="<c:url value="/js/jquery-ui.js"/>"></script>

<input type="hidden" name="applicationUrl" id="applicationUrl"
    value="${pageContext.request.contextPath}">

<div class="container sec-container middle-sec">
    <div class="form-fields row">
        <div class="col-md-12 col-sm-12 col-xs-12">
            <form:form class="form-horizontal policy-form" id="emailCommu-form"  method="POST" action="sendEmailMessage" commandName="emailForm">
                <div class="form-group">
                <h1 class="email-header">SiteMidner Email Notification</h1>
                <c:choose>
                    <c:when test="${not empty sMsg}">
                        <div class="email-Commu-SMsg">* ${sMsg}</div>
                    </c:when>
                    <c:otherwise>
                        <c:if test="${not empty eMsg}">
                            <div class="email-Commu-EMsg">* ${eMsg}</div>
                        </c:if>
                    </c:otherwise>
                </c:choose>
                <div class="form-emailCommu">
                    <label for="emailSub-txtArea" class="email-ContentHead">Enter
                        the Subject Line for the Email : </label>
                    <div class="email-sm-textDiv">
                        <form:textarea path="emailSubject" name="emailSubject" id="emailSubTxtArea"
                            placeholder="Email Subject"/>
                    </div>
                    <span><form:errors path="emailSubject" cssClass="error" /></span>

                </div>

                <div class="form-emailCommu">
                    <label for="emailBod-txtArea" class="email-ContentHead">Enter
                        the Message Body for the Email : </label>
                    <div class="email-sm-textDiv">
                        <form:textarea path="emailMsg" name="emailMsg" id="emailBodyTxtArea"
                            placeholder="Email Body"/>
                    </div>
                    <span><form:errors path="emailMsg" cssClass="error" /></span>

                </div>

                <div class="email-sendButton">
                    <input type="submit" class="styled-button" value="Send Email"></input>
                </div>
                </div>
            </form:form>

        </div>
        <!--form-fields close -->
    </div>
</div>

控制器代码:

@RequestMapping(value="/sendEmailMessage",method=RequestMethod.POST)
public ModelAndView sendEmailCommunication(@Valid @ModelAttribute("emailForm") EmailReqInfo emailInfo,BindingResult result,HttpServletRequest request){
    ModelAndView view = null;
    StringBuffer sMsg = new StringBuffer();
    StringBuffer eMsg = new StringBuffer();
    boolean isAdmin = false;
    try{
    String loggedInUser = request.getHeader("sm_user").trim();
     isAdmin = getUserAdminRights(request);

     if(result.hasErrors()){
         view = new ModelAndView("EmailCommunication");
         view.addObject("isAdmin", isAdmin);
         return view;
     }
     else{
        String emailSubject = emailInfo.getEmailSubject();
        String emailMsg  = emailInfo.getEmailMsg().replace("\n", "<br />\n");
    boolean status = emailService.sendEmailCommuncation(emailSubject,emailMsg);
    if(status){
        sMsg.append(" Sending SiteMinder Notification Email was Success.");
    }
    else{
        eMsg.append(" Oops! Something went wrong while sending Email Notification. Pls check logs");
    }
    }
    }
    catch(Exception ex){
        ex.printStackTrace();
        eMsg.append("Oops! Something went wrong while sending Email Notification. Pls check logs");
    }
    view = new ModelAndView("EmailCommunication");
    view.addObject("emailForm", new EmailReqInfo());
    view.addObject("isAdmin", isAdmin);
    view.addObject("sMsg", sMsg.toString());
    view.addObject("eMsg", eMsg.toString());
    return view;
}

电子邮件型号:

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotEmpty;

public class EmailReqInfo 
{

    @NotNull @NotEmpty
    @Size(min=1)
    private String emailSubject;
    @NotNull @NotEmpty
    private String emailMsg;
    public String getEmailSubject() {
        return emailSubject;
    }
    public void setEmailSubject(String emailSubject) {
        this.emailSubject = emailSubject;
    }
    public String getEmailMsg() {
        return emailMsg;
    }
    public void setEmailMsg(String emailMsg) {
        this.emailMsg = emailMsg;
    }
}

我在spring-mvc.xml中有必要的注释

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="false">
    <bean id="jacksonMessageConverter" 
      class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
  </mvc:message-converters>
  </mvc:annotation-driven>

修复验证所需的帮助。谢谢

2 个答案:

答案 0 :(得分:2)

@NotNull :检查该值是否为空,忽略内容。

@NotEmpty :检查该值是否为空,也不为空。如果它只有空格,则允许它不为空。

@NotBlank :检查值是否为空还是空,首先修剪该值。这意味着,它不会只允许空格

因此,如果您想验证某个字段不是null,而且它不只有空格而是文本,那么您应该使用@NotBlank。

这个例子正在运行,尝试做同样的事情:

<强>实体:

@Entity
@Table(name="EMPLOYEE")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Size(min=3, max=50)
    @Column(name = "NAME", nullable = false)
    private String name;

    @NotNull
    @DateTimeFormat(pattern="dd/MM/yyyy") 
    @Column(name = "JOINING_DATE", nullable = false)
    @Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
    private LocalDate joiningDate;

    @NotNull
    @Digits(integer=8, fraction=2)
    @Column(name = "SALARY", nullable = false)
    private BigDecimal salary;

    @NotEmpty
    @Column(name = "SSN", unique=true, nullable = false)
    private String ssn;
//getter & setter
}

<强>控制器:

@RequestMapping(value = { "/new" }, method = RequestMethod.POST)
    public String saveEmployee(@Valid Employee employee, BindingResult result,
            ModelMap model) {

        if (result.hasErrors()) {
            return "registration";
        }


        service.saveEmployee(employee);

        model.addAttribute("success", "Employee " + employee.getName() + " registered successfully");
        return "success";
    }

<强> registation.jsp

<h2>Registration Form</h2>

    <form:form method="POST" modelAttribute="employee">
        <form:input type="hidden" path="id" id="id"/>
        <table>
            <tr>
                <td><label for="name">Name: </label> </td>
                <td><form:input path="name" id="name"/></td>
                <td><form:errors path="name" cssClass="error"/></td>
            </tr>

            <tr>
                <td><label for="joiningDate">Joining Date: </label> </td>
                <td><form:input path="joiningDate" id="joiningDate"/></td>
                <td><form:errors path="joiningDate" cssClass="error"/></td>
            </tr>

            <tr>
                <td><label for="salary">Salary: </label> </td>
                <td><form:input path="salary" id="salary"/></td>
                <td><form:errors path="salary" cssClass="error"/></td>
            </tr>

            <tr>
                <td><label for="ssn">SSN: </label> </td>
                <td><form:input path="ssn" id="ssn"/></td>
                <td><form:errors path="ssn" cssClass="error"/></td>
            </tr>

            <tr>
                <td colspan="3">
                    <c:choose>
                        <c:when test="${edit}">
                            <input type="submit" value="Update"/>
                        </c:when>
                        <c:otherwise>
                            <input type="submit" value="Register"/>
                        </c:otherwise>
                    </c:choose>
                </td>
            </tr>
        </table>
    </form:form>

答案 1 :(得分:0)

我看到Hibernate Validators的问题。 @NotEmpty无论如何都在@NotNull之上。

尝试从表单中删除@NotEmpty验证限制,然后再次执行。