1

我需要帮助我正在使用 Spring 3 MVC 和 JSR303 进行表单验证。无论如何,在我工作之前,但不是在那之后停止工作。我创建了一个类来更简化地解析 JSON 格式 BindingResult 中的错误。现在我得到的是总是返回 false HasErrors getFieldErrors 总是空的,我没有收到错误。

我复制我的代码,看看你能不能帮帮我。

课堂留言

@Entity
@Table(name="messages")
public class Message 
{   
 @Id
 @GeneratedValue
 @Column(name="id")
 private long id;

 @Column(name="name") 
 @NotEmpty(message="El Nombre es obligatorio") @Size(min=3, max=150, message="El Nombre debe tener entre 3 y 150 caracteres")
 private String name;

 @Column(name="email")
 @NotEmpty(message="El Email es obligatorio") @Email(message="El Email no es válido")
 private String email;

 @Column(name="issue")
 @NotEmpty(message="El Asunto es obligatorio") @Size(min=3, max=150, message="El Asunto debe tener entre 3 y 150 caracteres") 
 private String issue;

 @Column(name="content")
 @NotEmpty(message="El Mensaje es obligatorio") @Size(min=3, max=150, message="El Mensaje debe tener entre 3 y 150 caracteres")
 private String content;

 @Column(name="ip")
 private String ip;

 @Column(name="user_agent")
 private String user_agent;

 @Column(name="moment")
 @Temporal(TemporalType.TIMESTAMP)
 private Date moment;

 @ManyToOne
 @JoinColumn(name="message_status_id")
 private @Valid MessageStatus messagestatus;
 //getters and setters

类消息状态:

@Entity
@Table(name="message_status")
public class MessageStatus {

 @Id
 @GeneratedValue
 @Column(name="id")
 private int id;

 @Column(name="name") 
 @NotEmpty(message="El Nombre es obligatorio") @Size(min=3, max=150, message="El Nombre debe tener entre 3 y 150 caracteres")
 private String name; 

 @OneToMany(mappedBy="messagestatus") //nombre de la varible de la otra entidad
 private Set<Message> messages;

类 MessageStatusDao:

@Repository
public class MessageStatusDao {

 public MessageStatusDao()
 {

 }

 @Transactional
 public void save(MessageStatus m) {
  Session s = HibernateUtil.getSession();
  s.beginTransaction();
  s.save(m);
 } 

 @SuppressWarnings("unchecked")
 @Transactional
 public List<MessageStatus> list() {
     Session s = HibernateUtil.getSession();
     s.beginTransaction();
     List<MessageStatus> ms = null;
     try {
         ms = (List<MessageStatus>)s.createQuery("from message_status").list();

     } catch (HibernateException e) {
         e.printStackTrace();
     }
     return ms;
 } 

 @Transactional
 public MessageStatus get(Integer id) {
     Session s = HibernateUtil.getSession();
     s.beginTransaction();
     return (MessageStatus)s.get(MessageStatus.class, id);
 } 

 @Transactional
 public void remove(Integer id) {
     Session s = HibernateUtil.getSession();
     s.beginTransaction();
     MessageStatus ms = (MessageStatus)s.get(MessageStatus.class, id);
     s.delete(ms);
 } 
}

控制器:

@Controller
@RequestMapping("/contact")
public class Contact 
{ 
 @Autowired
 private MessageStatusDao msDao;    

 @RequestMapping(method = RequestMethod.GET)
 public String printContact(ModelMap model) 
 {
  //Nombre de la vista a cargar
  String view = new String("contact");

  model.addAttribute("view", view);
  model.addAttribute("message", new Message());
  return "main-layout";
 } 

 @RequestMapping(value = "/add", method = RequestMethod.POST)
 public @ResponseBody FormResult addContact(@Valid Message message , BindingResult result, ModelMap model) 

 {
  FormResult formResult = new FormResult(result.hasErrors(), result.getFieldErrors());
  HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();

  //Comprobarmos el captcha
  String remoteAddr = request.getRemoteAddr();

  ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
  reCaptcha.setPrivateKey("6LehfOgSAAAAAFFYsdBXXbbl4kp6s0J6GUErCDWU");
  String challenge = request.getParameter("recaptcha_challenge_field");
  String uresponse = request.getParameter("recaptcha_response_field");

  ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

  if(!reCaptchaResponse.isValid()) {
   formResult.setHasErrors(true);
   formResult.addFormError("captcha", "Código captcha no válido.");
  }

  //Si no hay errores guardamos el Mensaje
  if(!formResult.isHasErrors()) {
   message.setIp(request.getRemoteAddr());
   message.setUser_agent(request.getHeader("user-agent"));

   Date now = Calendar.getInstance().getTime();
   message.setMoment(now);

   //Se obtiene un MessageStatus y se asigna al mensaje
   MessageStatus ms = msDao.get(1);
   message.setMessagestatus(ms);   

   // Se obtiene la sesion y se guarda
   Session s = HibernateUtil.getSession();
   s.beginTransaction(); 
   s.save(message);
   s.getTransaction().commit();   
   s.close();
  }

  return formResult;  
 }    

}

网页.xml:

<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://java.sun.com/xml/ns/j2ee 
        http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Spring Web MVC Application</display-name>

    <servlet>
        <servlet-name>bets-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>bets-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/bets-dispatcher-servlet.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <listener>                                                                                      
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener> 
</web-app>

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.omb</groupId>
    <artifactId>bets</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>bets Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <spring.version>3.2.2.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
            <optional>true</optional>
        </dependency>   

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <!-- Spring 3 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>   

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
            <scope>compile</scope>
        </dependency>   

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>ejb3-persistence</artifactId>
            <version>1.0.2.GA</version>
        </dependency>               

        <!-- Hibernate Validator -->
        <dependency>
           <groupId>org.hibernate</groupId>
           <artifactId>hibernate-annotations</artifactId>
           <version>3.4.0.GA</version>
           <scope>compile</scope>
        </dependency>

        <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>5.1.6</version>
           <scope>compile</scope>
        </dependency>

        <dependency>
           <groupId>org.slf4j</groupId>
           <artifactId>slf4j-log4j12</artifactId>
           <version>1.5.2</version>
           <scope>compile</scope>
        </dependency>

        <dependency>
           <groupId>javassist</groupId>
           <artifactId>javassist</artifactId>
           <version>3.4.GA</version>
           <scope>compile</scope>
        </dependency>       

        <!-- Jackson JSON Mapper -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>   

        <!-- reCaptcha -->
        <dependency>
            <groupId>net.tanesha.recaptcha4j</groupId>
            <artifactId>recaptcha4j</artifactId>
            <version>0.0.7</version>
        </dependency>                           
    </dependencies>

    <build>
        <finalName>bets</finalName>
    </build>

</project>

调度程序-servlet.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <context:component-scan base-package="com.omb.bets.web.pages" />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>

        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

    <bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
            <list><value>/WEB-INF/config.properties</value></list>
        </property>
    </bean>     

    <bean id="messagestatusdao" class="com.omb.bets.model.message.MessageStatusDao" />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources/ directory -->
    <mvc:resources mapping="/assets/**" location="/assets/" />

    <mvc:annotation-driven />
</beans>

联系人.jsp

        <div id="form-section">
            <form:form method="post" commandName="message" action="contact/add" class="form-horizontal">
                <fieldset>
                    <legend>Contacto</legend>

                    <div id="name-control" class="control-group">
                        <form:label path="name" class="control-label control-label-small-margin" >Nombre:</form:label>
                        <div class="controls">
                            <form:input path="name" class="input-xlarge" placeholder="Nombre y apellidos..."  />
                            <form:errors path="name" cssClass="error help-line" />
                            <label id="name-msg" class="help-inline form-error hide"></label>
                        </div>
                    </div>

                    <div id="email-control" class="control-group">
                        <form:label path="email" class="control-label control-label-small-margin" >Email:</form:label>
                        <div class="controls">
                            <form:input path="email" type="email" class="input-xlarge" placeholder="example@gmail.com"  />
                            <form:errors path="email" cssClass="error" />
                            <label id="email-msg" class="help-inline form-error hide"></label>
                        </div>
                    </div>

                    <div id="issue-control" class="control-group">
                        <form:label path="issue" class="control-label control-label-small-margin" >Asunto:</form:label>

                        <div class="controls">
                            <form:input path="issue" class="input-xlarge" placeholder="Motivo del contacto..."  />
                            <form:errors path="issue" cssClass="error" />
                            <label id="issue-msg" class="help-inline form-error hide"></label>
                        </div>
                    </div>                      

                    <div id="content-control" class="control-group">
                        <form:label path="content" class="control-label control-label-small-margin" >Mensaje:</form:label>
                        <div class="controls">
                            <form:textarea path="content" rows="3" class="input-xlarge" placeholder="Escribe tu consulta..."  />
                            <form:errors path="content" cssClass="error" />
                            <label id="content-msg" class="help-inline form-error hide"></label>
                        </div>
                    </div>  

                    <div id="captcha-control" class="control-group">
                        <label class="control-label control-label-small-margin">Captcha:</label>
                        <div id="captcha-controls" class="controls">    
                            <%
                              ReCaptcha c = ReCaptchaFactory.newReCaptcha("6LehfOgSAAAAABo20sV7W7XJQW3Qx86LAdO6RAm7", "6LehfOgSAAAAAFFYsdBXXbbl4kp6s0J6GUErCDWU", false);
                              out.print(c.createRecaptchaHtml(null, null));
                            %>                          
                            <label id="captcha-msg" class="help-inline form-error hide"></label>
                        </div>
                    </div>

                    <div class="form-actions">
                        <button class="btn btn-primary pull-right" type="submit">Enviar!</button>
                    </div>                              
                </fieldset>
            </form:form>
        </div> <!-- /.form-section -->

添加.js

$('form').on("submit", function(event){
    event.preventDefault();
    var $form = $(this);
    // Desactivar boton
    $.ajax({
        url: $form.attr("action"),
        type: 'POST',
        data: $form.serialize(),
        dataType: 'json',
        cache: false
    }).done(function(data){ 
        //Borramos todos los errores, por si habia alguno de antes,
        $form.find("label[id$='-msg']").html('').addClass('hide');  
        $form.find("div[id$='-control']").removeClass('error');
        if(data.hasErrors){//Si hay errores de formulario
            //Recorremos todos los errores
            $.each(data.form_errors, function(key, value){
                $('#'+value.name+'-control').addClass('error');
                $('#'+value.name+'-msg').append('<br />' + value.message).removeClass('hide');
            });     
            Recaptcha.reload();
        }else {// Si no hay errores de formulario
            $form.find("[class^='input']").val(''); 
            $('#form-section').fadeOut("slow", function() {
                $('#form-result').fadeIn("slow");
            });

        }
    });
});

正如我之前所说,我现在返回一个错误,而不是因为他们没有得到任何异常。你能帮我吗?

非常感谢和最好的问候。

4

1 回答 1

0

请看这里:如何在 Spring 4 中打开注释驱动的验证?

In short: check if you have included all the validation API JAR dependencies into the final package.

于 2015-01-13T04:04:18.263 回答