1

我想在 Spring MVC Web App 中实现自定义验证,但我有多个问题,我有两个实体作为

@Entity
public class Foo implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;        
    private String title;       
    @ManyToMany(fetch=FetchType.EAGER, cascade = { CascadeType.MERGE })
    @JoinTable(name = "foos_bars",
                joinColumns = @JoinColumn(name = "foos_id"),
                inverseJoinColumns = @JoinColumn(name = "bars_id"))
    private List<Bar> bars;
}

@Entity 公共类 Bar 实现 Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@ManyToMany(mappedBy = "bars", cascade = { CascadeType.MERGE })
private List<Foo> foos;

}

我的自定义验证器是

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;   

public class FooValidator implements Validator{

    @Override
    public boolean supports(Class<?> clazz) {
        // TODO Auto-generated method stub
        return Foo.class.equals(clazz);
    }

    @Override
    public void validate(Object object, Errors errors) {
        // TODO Auto-generated method stub
        Foo foo = (Foo) object;

        if (foo.getTitle().length() < 5 || foo.getTitle().length() > 50) {
            errors.rejectValue("title", "foo.title", ErrorConstant.TITLE_ERROR);
        }
    }

}

1-我想用一些 HTML 和 CSS 显示一些错误消息

 ErrorConstant.TITLE_ERROR = "<span class=\"form-help form-help-msg text-red\">"
                + "Valid title is 15-50 chars"
                + "<i class=\"form-help-icon icon icon-error\"></i></span>";

但现在无法在我的控制器中完成工作

@Controller
@RequestMapping(value = "/foo")
public class FooController {

    @Autowired
    private FooService fooService;  
    @Autowired
    private FooValidator fooValidator;

    @InitBinder
    public void initBinderOne(WebDataBinder binder) {
        binder.addValidators(fooValidator);// custom validator added here
        binder.registerCustomEditor(Bar.class,
                new PropertyEditorSupport() {
                    @Override
                    public void setAsText(String text) {
                        // replace the dao with your appropriate repository call
                        Bar bar = fooService.getById(Long
                                .parseLong(text));
                        setValue(bar);
                    }
                });     
    }   

    @ModelAttribute("bar")
    public Bar constructBar() {
        return new Bar();
    }

    @ModelAttribute("foo")
    public Foo constructFoo() {
        return new Foo();
    }           

    @RequestMapping(value = "/add-foo", method = RequestMethod.GET)
    public String showFooForm(Model model) {
        model.addAttribute("bars", fooService.getAllBars());            
        return "add-foo";
    }   

    @RequestMapping(value = "/add-foo", method = RequestMethod.POST)
    public String addFooDetail(Model model, @ModelAttribute("foo") @Valid Foo foo, Errors errors) {

        if (errors.hasErrors()) {
            model.addAttribute("foo", foo);
            model.addAttribute("bars", fooService.getAllBars());
            return "add-foo";

        }else{              
            fooService.saveFoo(foo);    
            return "redirect:/";

        }

    }       
}

形式是

<form:form commandName="foo" class="form" id="add-foo">
    <form:input path="title"/>
    <form:errors path="title"/>
    <button>Add</button>        
</form:form>

此时我运行应用程序时出现错误

2- java.lang.IllegalStateException:Validator [com.exam.FooValidator@1e2c656] 的目标无效:Bar [title=null]

跟踪是

java.lang.IllegalStateException: Invalid target for Validator [com.exam.FooValidator@1e2c656]: Bar [title=null]
    at org.springframework.validation.DataBinder.assertValidators(DataBinder.java:516)
    at org.springframework.validation.DataBinder.addValidators(DataBinder.java:527)
    at com.eaxm.FooController.initBinderOne(FooController.java:36)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
    at org.springframework.web.method.annotation.InitBinderDataBinderFactory.initBinder(InitBinderDataBinderFactory.java:62)
    at org.springframework.web.bind.support.DefaultDataBinderFactory.createBinder(DefaultDataBinderFactory.java:53)
    at org.springframework.web.method.annotation.ModelFactory.updateBindingResult(ModelFactory.java:251)
    at org.springframework.web.method.annotation.ModelFactory.updateModel(ModelFactory.java:235)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.getModelAndView(RequestMappingHandlerAdapter.java:879)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:782)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

我发现应该有@InitBinder以这种方式声明名称的新方法

@InitBinder("foo")
    public void initBinderValidator(WebDataBinder binder) {
        binder.addValidators(fooValidator);     
    }

我仍然得到与上述相同的错误。请对这些问题的任何解决方案

4

1 回答 1

0

我认为您只需要在验证器的支持方法中包含 Foo 和 Bar 类,如下所示:

@Override
public boolean supports(Class<?> clazz) {
    return Foo.class.isAssignableFrom(clazz) ||
           Bar.class.isAssignableFrom(clazz);
}
于 2016-07-21T19:08:24.627 回答