【问题标题】:Validating a form in JSP在 JSP 中验证表单
【发布时间】: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


    【解决方案1】:

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

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

    读者文摘版:

    不要定义自己的 urlMapping 和调度程序中的所有内容,而是使用 &lt;mvc:annotation-driven/&gt;

    然后,您无需从 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 示例应用程序的当前版本以获取详细示例。

    【讨论】:

    • 我应该在我的代码中进行哪些更改才能使其正常工作?你能告诉我吗?
    • 这里有一个又快又脏的版本,详细例子请查看 spring 教程。
    • 嗨@Affe。我改变了验证表单的方式。我现在使用Validator 而不是HibernateValidator,因为我目前必须使用SimpleFormController,尽管它已经被弃用了。我刚刚用Validator 实现了表单验证方法,它工作得很好。非常感谢您的建议。我确实采用了错误的方式来验证我可以从您的回答中知道的表格。你建议的方法我以后肯定会付诸实践的。
    猜你喜欢
    • 1970-01-01
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多