无法获得@Valid参数

时间:2015-02-04 12:30:25

标签: java hibernate validation spring-mvc bean-validation

我正在使用spring MVC 4和tomcat 7.

我是java的新手,对emailTo参数有一个验证问题(可能是绑定),我希望对其进行验证(在UI中)。 我已经花了我和其他程序员的时间,但没有成功。

对于emailTo,BindingResult结果为空,但在尝试将其添加到数据库时失败抛出异常(由于@NotNull注释)。 意思是,注释工作正常,但验证不是......

奇怪的是,验证适用于modifiedSince参数(@Temporal(TemporalType.TIMESTAMP)),但不适用于emailTo

Oracle的桌面类通过hibernate(DBLayer项目下的Task.java):

    package entities;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Index;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;

import enums.TaskIdentifierType;
import enums.TaskPriority;
import enums.TaskStatus;
import enums.TaskType;

@Entity
@Table(name="TASK", indexes= {@Index(columnList="TITLE"),
                              @Index(columnList="TYPE"),
                              @Index(columnList="STATUS")})
@SequenceGenerator(initialValue = 1, name = "taskIdGen", sequenceName = "TaskSequence")
public class Task {

    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE)
    @Column(name="TASK_ID")
    private int taskId;

    @Column(name="TITLE")
    private String taskTitle;

    @Enumerated(EnumType.STRING)
    @Column(name="TYPE")
    private TaskType type;

    @Enumerated(EnumType.STRING)
    @Column(name="STATUS")
    private TaskStatus status;
    .
    .
    .   
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name="MODIFIED_SINCE")
    private Date modifiedSince;
    .
    .
    .
    @Column(name="VALID_PHRASE")
    private String validPhrase;

    @Email
    @NotNull
    @NotEmpty
    @Column(name="EMAIL_TO")
    private String emailTo;

    @Enumerated(EnumType.STRING)
    @Column(name="PRIORITY")
    TaskPriority priority;

    @OneToMany(targetEntity=ResultItem.class, mappedBy="task", fetch=FetchType.LAZY, cascade=CascadeType.DETACH)
    private Collection<ResultItem> resultItems;

    public Task() throws ParseException{
        timestamp = new Date();
        status = TaskStatus.NEW;
        priority = TaskPriority.NORMAL;
        resultItems = new ArrayList<ResultItem>();  
        identifierType = TaskIdentifierType.TS_ID;
        type = TaskType.DB;
    }
    .
    .
    .
LinkCheckerGUI项目下的TaskController.java:

@RequestMapping(value = "task/new", method = RequestMethod.POST)
    public String processCreationForm(@Valid @ModelAttribute("taskModel")NewTaskModel taskModel, BindingResult result, SessionStatus status) {
        System.out.println("---------in task controller");

        if (taskModel == null){
            System.out.println("Task is null");
        }
        else{
            System.out.println("------------task email to=" + taskModel.getTask().getEmailTo().toString());
        }

        System.out.println("--------------all Errors:" + result.getFieldErrors());

    if (result.hasErrors()) {
            for(ObjectError oe : result.getAllErrors()){
                System.out.println("-----------------error:"+oe.toString());    
    }
            System.out.println("-------Error found in new task values");/////////////////
            return "task/newTask";
        } 

        try {

            taskManager.addTask(taskModel.getTask());
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }
        return "redirect:new";
    }
LinkCheckerGUI项目下的

newTask.jsp:

    <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

    <html lang="en">
    <head>
    <meta 

http-equiv="Content-Type" content="text/html; charset=windows-1255">
    <title>LinkChecker</title>
    </head>
    <%-- <jsp:include page="headersMenu.jsp"/> --%>
    <jsp:include page="../fragments/staticFiles.jsp"/>
    <body>
    <h2><fmt:message key="task.add.title"/></h2>
    <div class="container">
    <jsp:include page="../fragments/bodyHeader.jsp"/>
    <form:form modelAttribute="taskModel" method="POST">
        <table>
        <tr>
            <td><form:label path="task.taskTitle"/>Task name:</td>  
                <td><form:input path="task.taskTitle"/></td>
            </tr> 

            <tr>
            <td><form:label path="task.invalidPhrase"/>Invalid Phrase:</td>  
                <td><form:input path="task.invalidPhrase"/></td>
            </tr>
        .
        .
        . 
            <tr>
            <td><form:label path="task.validPhrase"/>Valid Phrase:</td>  
                <td><form:input path="task.validPhrase"/></td>
            </tr> 
            <tr>
            <td><form:label path="task.modifiedSince" class="validationError"/>Modified Since:</td>  
                <td><form:input path="task.modifiedSince"/></td>
                <td><form:errors path="task.modifiedSince" cssClass="validationError"/></td>
            </tr>
            .
            .
            .
            <tr>
                <td></td>
                <td style="color: red; font-weight: bold;"><form:label path="task.emailTo"/>Email To:</td>  
                <td class="validationError"><form:label path="task.emailTo"/>Email To:</td>  
                <td><form:input path="task.emailTo"/></td>
                <td><form:errors path="task.emailTo" cssClass="validationError"/></td>
            </tr>
        </table>

                <input type="submit" id="submit" value="Submit"/>
    </form:form>
    </div>
</body>
</html>

这是我的两个相关项目(DBLayer和LinkCheckerGUI)的相关代码。

在这种情况下,点击&#39;提交&#39;:

  1.   

    在表单中,我收到了&#34; Modified Since&#34;的请求验证消息。 field(我把它留空了,因为它的定义是@Temporal(TemporalType.TIMESTAMP))。

  2. 输出:

  3.   

    所有错误:[对象中的字段错误&#39; taskModel&#39; on field&#39; task.modifiedSince&#39 ;:拒绝值[];代码[typeMismatch.taskModel.task.modifiedSince,typeMismatch.task.modifiedSince,typeMismatch.modifiedSince,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable:codes [taskModel.task.modifiedSince,task.modifiedSince];参数[];默认消息[task.modifiedSince]];默认消息[无法转换类型&#39; java.lang.String&#39;的属性值要求的类型&#39; java.util.Date&#39; for property&#39; task.modifiedSince&#39 ;;嵌套异常是org.springframework.core.convert.ConversionFailedException:无法从类型java.lang.String转换为类型@javax.persistence.Temporal @javax.persistence.Column java.util.Date for value&#39;&# 39 ;;嵌套异常是java.lang.IllegalArgumentException]]   -----------------错误:对象&#39; taskModel&#39;中的字段错误on field&#39; task.modifiedSince&#39 ;:拒绝值[];代码[typeMismatch.taskModel.task.modifiedSince,typeMismatch.task.modifiedSince,typeMismatch.modifiedSince,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable:codes [taskModel.task.modifiedSince,task.modifiedSince];参数[];默认消息[task.modifiedSince]];默认消息[无法转换类型&#39; java.lang.String&#39;的属性值要求的类型&#39; java.util.Date&#39; for property&#39; task.modifiedSince&#39 ;;嵌套异常是org.springframework.core.convert.ConversionFailedException:无法从类型java.lang.String转换为类型@javax.persistence.Temporal @javax.persistence.Column java.util.Date for value&#39;&# 39 ;;嵌套异常是java.lang.IllegalArgumentException]   -------在新任务值中发现错误

    1.   

      没有其他验证失败,虽然emailTo应该失败,因为我也把它留空了。

    2. 添加绑定时(在taskController.java中):

      @InitBinder
      public void initBinder(WebDataBinder binder) {
          //This WebDataBinder set the Date parameters to null in case they are empty
          SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
          dateFormat.setLenient(false);
      
          // true passed to CustomDateEditor constructor means convert empty String to null
          binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
      }
      

      modifiedSince的验证消息按预期消失,未显示其他消息,输出为:

        

      ------------任务电子邮件至= --------------所有错误:[]

      意味着,结果不会出现任何错误(对于emailTo参数)。

      如果我从控制器中删除try / catch(对于addTask方法),它将会粉碎(抛出异常),因为emailTo参数为空并且无法将其添加到数据库中(如预期)。

      ****我创建了一个简单的类,它工作正常。有没有理由说它没有工作实体课?

      我很感激你的帮助......

      提前致谢!

      麦克

0 个答案:

没有答案