【发布时间】:2012-06-30 18:52:09
【问题描述】:
在HibernateValidator 的帮助下,我正在使用JSP 中的Spring 和Hibernate(使用SimpleFormController)验证一个简单的表单,正如here 所解释的那样。只包含一个字段的表单如下。
<%@page contentType="text/html" pageEncoding="UTF-8" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<form:form method="post" id="userForm" name="userForm" action="Temp.htm" commandName="validationForm">
<table>
<tr>
<td>User Name:<font color="red"><form:errors path="userName" /></font></td>
</tr>
<tr>
<td><form:input path="userName" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
以下是定义验证条件的命令类。
package validators;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
final public class ValidationForm
{
@NotEmpty(message="Must not be left blank.")
@Size(min = 1, max = 2)
private String userName;
public void setUserName(String userName)
{
this.userName = userName;
}
public String getUserName()
{
return userName;
}
}
以下是dispatchar-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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
<bean id="tempService" class="usebeans.TempServiceImpl" />
<bean id="tempController" class="controller.Temp" p:tempService-ref="tempService" p:formView="Temp" p:successView="Temp"/>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
<prop key="Temp.htm">tempController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
其中TempService 是一个只包含一个方法add(ValidationForm validationForm){...} 的接口,TempServiceImpl 是一个实现TempService 接口的类。
控制器类Temp如下。
package controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import usebeans.TempService;
import validators.ValidationForm;
@SuppressWarnings("deprecation")
final public class Temp extends SimpleFormController
{
private TempService tempService=null;
public Temp()
{
setCommandClass(ValidationForm.class);
setCommandName("validationForm");
}
//This method may not be necessary.
public void setTempService(TempService tempService)
{
this.tempService = tempService;
}
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("validationForm") @Valid Object command, BindException errors) throws Exception
{
ValidationForm validationForm=(ValidationForm) command;
tempService.add(validationForm); //May not be necessary.
if(errors.hasErrors()) //Never evaluates to true even though the text box on the form is left blank.
{
System.out.println("User Name : "+validationForm.getUserName());
//Or do something.
}
else
{
//Do some stuff such as database operations like insert, update or delete.
}
ModelAndView mv=new ModelAndView("Temp", "validationForm", validationForm);
return mv;
}
@Override
protected ModelAndView showForm(HttpServletRequest request, HttpServletResponse response, BindException errors) throws Exception
{
ModelAndView mv=new ModelAndView("Temp", "validationForm", new ValidationForm());
return mv;
}
}
现在,这里发生的情况是,当通过单击表单上的唯一提交按钮提交表单时,将调用控制器类 Temp 中的 onSubmit() 方法,我在其中强加了 if条件if(errors.hasErrors()){}。
因此,如果表单上唯一的 TextField 为空,则正在呈现的表单包含验证错误,if 条件应评估为 true,并应显示指定的错误消息(如 ValidationForm 中指定的那样) @NotEmpty(message="Must not be left blank.") 类),但这永远不会发生 [ValidationForm 的对象可通过 onSubmit() 方法的 Object command 参数获得]。无论文本框是否包含值,条件都不会计算为真。
我在这里缺少什么?我觉得我使用 HibernateValidator 的方式错误。任何提示或指南都会对我有所帮助。
[应用程序运行时没有错误,但要验证的表单未通过验证]
【问题讨论】:
标签: java spring hibernate jsp hibernate-validator