当我使用jQuery和spring 4进行服务器端表单验证时,我遇到了问题。每次"结果" (BindingResult的对象)将出现零错误结果。
下面我证明了我的代码以便更好地理解。 我的jsp代码是
<div class="registerForm">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</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>
我的脚本代码是
$.ajax({
url: "${pageContext.request.contextPath}/register",
data: $('#regForm').serialize(),
type: "POST",
success: function(result) {},
error: function(XMLHttpRequest, textStatus, errorThrown){}
});
我的控制器代码是
@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;
}
我的bean对象
public class UserRegister {
@NotEmpty @NotNull
private String username;
@NotEmpty @NotNull
private String password;
@NotEmpty @Email @NotNull
private String emailAddress;
setter and getters....
}
我是否需要进行任何其他配置或其他操作才能正确验证?
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>
答案 0 :(得分:1)
带有属性(用户名,电子邮件等)字段的userReg模型对象是否已提交给服务器?
如果没有,表单字段可能无法正确绑定到模型对象
尝试
<form:form action="register" method="post" commandName="userRegister">
此外,输入字段需要具有到模型对象的映射
<form:input path="username" />
还要确保在上下文文件中设置
<mvc:annotation-driven />
同时确认验证器jar存在于pom.xml
中<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
或
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
</dependency>
请列出spring xml配置文件(其中包含以下行的文件)?
<mvc:annotation-driven />