Spring Validator不支持命令类

时间:2013-05-21 09:01:20

标签: java spring

我认为这个问题很常见,但出于某些原因,我无法解决这个问题。

这是我得到的错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'reverseController' defined in ServletContext resource [/WEB-INF/app-servlet.xml]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: Validator [FormValidator@6b3ded0d] does not support command class [ReverseString]

这是我的FormValidator类中的supports方法:

public boolean supports(Class clazz) {
    return ReverseController.class.isAssignableFrom(clazz);
}

这是我的app-servlet.xml上的bean定义:

<bean id="reverseController" class="ReverseController">     
   <property name="commandName"><value>reverseString</value></property>
   <property name="commandClass"><value>ReverseString</value></property>        
   <property name="formView"><value>reverse</value></property>
   <property name="successView"><value>reverseResult</value></property>
   <property name="validator"><bean class="FormValidator" /></property>

最后,这是我的ReverseController的主要部分:

 @Service
public class ReverseController extends SimpleFormController {

    public ReverseController() {
        //setCommandClass(ReverseString.class);
        //setCommandName("reverseString");
    }

    private ReverseString reverseStringMaster;

    @Autowired
    public void setWriter(ReverseString reverseStringMaster) {
        this.reverseStringMaster = reverseStringMaster;
    }

    protected ModelAndView onSubmit(HttpServletRequest request,
        HttpServletResponse response, Object command, BindException errors) {

        ReverseString revString = (ReverseString) command;

        return new ModelAndView(getSuccessView(),"reversedString",  revString);
    }

    public void init() {
        System.out.println("Done");
    }


}

知道可能导致该问题的原因是什么?

3 个答案:

答案 0 :(得分:3)

这是在每个请求上验证的命令类的实例 - 因为它填充了表单数据。控制器本身未经过验证。

因此,supports()中的FormValidator方法实际上应该是:

public boolean supports(Class clazz) {
    return ReverseString.class.isAssignableFrom(clazz);
}

答案 1 :(得分:0)

您是否为此commandClass变量添加了 getter和setter 以及更好?如果是这样,您可能需要从setter中删除@spring.validator type="required"方法法。

答案 2 :(得分:0)

为app-servlet.xml试用此代码 1.像这样定义你的控制器。
2.然后使用reverseController调用ReverseController类方法。

<managed-bean>
        <managed-bean-name>reverseController</managed-bean-name>
        <managed-bean-class>com.action.ReverseController</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>