简体   繁体   English

使用AJAX的Spring 4.0表单验证问题

[英]Spring 4.0 form validation issue using AJAX

I am facing problem when i am doing server side form validation using jQuery and spring 4. Every time "result" (object of BindingResult) is coming with zero error result. 我在使用jQuery和spring 4进行服务器端表单验证时遇到问题。每次“结果”(BindingResult的对象)出现零错误结果时。

Below I am proving my code for better understanding. 下面,我证明我的代码可以更好地理解。 my jsp code is 我的jsp代码是

  <div class="registerForm">
                      <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="myModalLabel">Please Register</h4>
                      </div>
                      <div class="modal-body">
                            <form class="form-signin" id="regForm" commandName="userRegister">
                                <div class="reg-error error"></div><div class="reg-success success"></div>
                                <input type="text" name="username" class="input-block-level" placeholder="Username">
                                <input type="text" name="emailAddress" class="input-block-level" placeholder="Email address">
                                <input type="text" name="confirmEmailAdd" class="input-block-level" placeholder="Confirm Email address">
                                <input type="password" name="password" class="input-block-level" placeholder="Password">
                            </form>
                      </div>
                      <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary submitRegister">Register</button>
                      </div>
                  </div>

my script code is 我的脚本代码是

 $.ajax({
                url: "${pageContext.request.contextPath}/register",    
                data: $('#regForm').serialize(), 
                type: "POST",
                success: function(result) {},
                error: function(XMLHttpRequest, textStatus, errorThrown){}
            });

My controller code is 我的控制器代码是

@RequestMapping(value="/register", method = RequestMethod.POST)
    public @ResponseBody 
    ValidationResponse register(Model model, @ModelAttribute("userRegister") @Valid UserRegister userReg, BindingResult result) {
        ValidationResponse res = new ValidationResponse();

        if(result.hasErrors()){
            res.setStatus("FAIL");
            List<FieldError> allErrors = result.getFieldErrors();
            List<ErrorMessage> errorMesages = new ArrayList<ErrorMessage>();
            for (FieldError objectError : allErrors) {
                errorMesages.add(new ErrorMessage(objectError.getField(), objectError.getField() + "  " + objectError.getDefaultMessage()));
            }
            res.setErrorMessageList(errorMesages);

        } else {
            res.setStatus("SUCCESS");
        }
        return res;
    }

My bean object 我的豆对象

public class UserRegister {

    @NotEmpty @NotNull
    private String username;

    @NotEmpty @NotNull
    private String password;

    @NotEmpty @Email @NotNull
    private String emailAddress;

setter and getters....
}

Do i need to do any other configuration or something else to get it validated properly? 我是否需要做任何其他配置或其他事情才能正确验证它?

app-servlet.xml APP-servlet.xml中

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


    <context:property-placeholder location="classpath:database.properties" />
    <context:component-scan base-package="com.app" />

    <tx:annotation-driven transaction-manager="hibernateTransactionManager"/>

    <bean id="myAuthenticationSuccessHandler" class="com.app.security.handler.MySimpleUrlAuthenticationSuccessHandler" />
    <bean id="myAuthenticationFailureHandler" class="com.app.security.handler.MySimpleUrlAuthenticationFailureHandler" />

    <bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${database.driver}" />
        <property name="url" value="${database.url}" />
        <property name="username" value="${database.user}" />
        <property name="password" value="${database.password}" />
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>             
            </props>
        </property>
    </bean>

    <!-- bind your messages.properties
    <bean class="org.springframework.context.support.ResourceBundleMessageSource"
        id="messageSource">
        <property name="basename" value="messages" />
    </bean>
         -->
</beans>

Is the userReg model object with the attributes (username, email etc) fields getting submitted to the server? 具有属性(用户名,电子邮件等)字段的userReg模型对象是否已提交到服务器?

If not, The form fields may not be getting bound correctly to the model object 否则,表单字段可能无法正确绑定到模型对象

Try 尝试

 <form:form action="register" method="post" commandName="userRegister">

Also, the input fields needs to have the mapping to the model object 另外,输入字段需要具有到模型对象的映射

<form:input path="username" /> 

Also ensure that is set in the context file 还要确保在上下文文件中设置了

<mvc:annotation-driven />

Here is a demo : http://www.codejava.net/frameworks/spring/spring-mvc-form-validation-example-with-bean-validation-api 这是一个演示: http : //www.codejava.net/frameworks/spring/spring-mvc-form-validation-example-with-bean-validation-api

Also confirm that the validator jars are present in pom.xml 还要确认pom.xml中存在验证器jar

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.1.0.Final</version>
</dependency>

or 要么

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-validator</artifactId>
   <version>5.0.1.Final</version>
</dependency>

Can you please list the spring xml configuration file (the file that has the below line in it)? 您能否列出spring xml配置文件(其中包含以下行的文件)?

 <mvc:annotation-driven />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM