Announcement Announcement Module
Collapse
No announcement yet.
Spring validation Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Spring validation

    Hi I'm upgrading an existing app where the controllers extends SimpleFormController and validation was "automagically" triggered from the bean declaration:
    Code:
    	<bean id="exampleValidator" class="ExampleValidator">
    	</bean>
    
    	<bean id="exampleController" class="ExampleController">
    		<property name="validator">
    			<ref bean="exampleValidator" />
    		</property>
    		<property name="sessionForm">
    			<value>true</value>
    		</property>
    		<property name="commandName">
    			<value>example</value>
    		</property>
    		<property name="commandClass">
    			<value>ExampleForm</value>
    		</property>
    		<property name="formView">
    			<value>example</value>
    		</property>
    	</bean>
    With this validation is nicely handled without any extra checks in the controller.

    Now I'm trying to achieve roughly the same behaviour using annotations and @Controller without having to write code like
    Code:
    new ExampleValidator.validate(request, bindingResponse);
    if(bindingResponse.hasErrors())
     return retryView;
    instead i would like to write something like using the @Valid annotation on the form

    Code:
    	@Autowired
    	private Validator exampleValidator;
    	
    	@InitBinder
    	public void initBinder(WebDataBinder dataBinder) {
    		dataBinder.setValidator(exampleValidator);
    	}
    
    	@RequestMapping(method=RequestMethod.POST)
    	public ModelAndView handleFormSubmit(HttpServletRequest request, HttpServletResponse response,@ModelAttribute("exmple") @Valid  ExampleForm exampleForm, BindingResult result) throws Exception {
    
    ...
    ...
           return successView;
    }
    Is this possible?

  • #2
    Have y ou read the reference guide? Chapter 15.12.1 mvc:annotation-driven explains how to do that (and it is basically what you have written above).

    Comment


    • #3
      Yes thank you I have read that! But can you please guide me how to configure the validate attribute if that is the way to do it (or why my example doesn't work)? I do not want a "global validator" but a specific validator for each controller.

      Comment


      • #4
        Got it working with @Valid but has anyone got an idea not having to do
        Code:
        		if(result.hasErrors()){
        			return retryView;
        		}
        but instead letting the controller automatically reload the view (as happens when using simpleFormController and the validator injection)?

        Comment

        Working...
        X