在JSP中验证表单

时间:2012-06-30 18:52:10

标签: java spring hibernate jsp hibernate-validator

我正在使用Spring中的Spring和Hibernate验证一个简单的表单(使用SimpleFormController),并在HibernateValidator的帮助下解释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;
    }
}

现在,这里发生的事情是,当单击表单上的唯一提交按钮提交表单时,将调用控制器类onSubmit()中的Temp方法,其中我强加if条件if(errors.hasErrors()){}

因此,如果表单上的唯一TextField为空,则呈现的表单包含验证错误,if条件应评估为true,并且应显示指定的错误消息(如{ {1}}类ValidationForm)但这从未发生[ @NotEmpty(message="Must not be left blank.")的对象可通过ValidationForm方法的Object command参数获得 ]。无论文本框是否包含值,条件永远不会计算为真。

我在这里缺少什么?我觉得我正在按照错误的方式使用onSubmit()。任何提示或指南对我都有帮助。

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

1 个答案:

答案 0 :(得分:1)

将@Valid放在方法参数上不适用于从CommandController及其子项(例如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示例应用程序。