0

我在 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。任何提示或指南都会对我有所帮助。

[应用程序运行没有错误,但要验证的表单未验证]

4

1 回答 1

1

CommandController将 @Valid 放在方法参数上不适用于从及其子级扩展的老式控制器(例如, SimpleFormController)。它是 的一个功能AnnotationMethodHandlerAdapter,因此您需要使用带注释的控制器才能使其工作。

(您必须禁止对该类的弃用警告是有原因的!:))

读者文摘版:

而不是定义自己的 urlMapping 和调度程序中的所有内容<mvc:annotation-driven/>

然后,您无需从 SimpleFormController 扩展,只需创建一个常规类并使用 @Controller 注释它,并使用 @RequestMapping 注释您的方法。

@Controller
@RequestMapping("/Temp.htm")
public class Temp {

@RequestMapping(method=RequestMethod.GET)
public ModelAndView getForm() {
  ModelAndView mv=new ModelAndView("Temp", "validationForm", new ValidationForm());
  return mv;
}

@RequestMapping(method=RequestMethod.POST)
public ModelAndView postForm(@Valid ValidationForm validationForm, BindingResult errors) {
        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;
}

互联网上有大量教程,其内容比我在这里复制的要多得多。查看 Spring PetClinic 示例应用程序的当前版本以获取详细示例。

于 2012-06-30T19:02:28.773 回答