我在 JSP 中使用 Spring 和 Hibernate 验证一个简单的表单(使用),并在此处解释SimpleFormController
的帮助下。只包含一个字段的表格如下。HibernateValidator
<%@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" />
whereTempService
是只包含一个方法的接口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;
}
}
现在,这里发生的情况是,当通过单击表单上的唯一提交按钮提交表单时,将调用onSubmit()
控制器类Temp
中的方法,在其中我强加一个if
条件if(errors.hasErrors()){}
。
因此,如果表单上唯一的 TextField 为空,则正在呈现的表单包含验证错误,并且if
应将条件评估为 true,并应显示指定的错误消息(如ValidationForm
类中指定的那样@NotEmpty(message="Must not be left blank.")
)但这永远不会发生 [对象的ValidationForm
可以通过方法的Object command
参数获得onSubmit()
。无论文本框是否包含值,条件都不会计算为真。
我在这里想念什么?我觉得我遵循了错误的使用方式HibernateValidator
。任何提示或指南都会对我有所帮助。
[应用程序运行没有错误,但要验证的表单未验证]