Spring Form: select bean according to params
Asked Answered
G

1

0

I've got a question concerning Spring forms (with Thymeleaf, to be specific).
I know that I can use only one bean at a time to back a form in Spring, so I thought it would be nice to let the Controller select which bean should be bound to the form,depending on which parameters are sent. But instead of writing a new RequestMapping for every new param, I wondered if I could somehow map the params only to the ModelAttribute itself.

I thought of something like this:

@Controller
public class FormController{

@ModelAttribute("bean", params={"type=bean1"}) //this declaration is invalid
public IBean loadEmptyModelBean(){
    return new Bean1();
}
@ModelAttribute("bean", params={"type=bean2"})
public IBean loadEmptyModelBean(){
    return new Bean2();
}

//..

@RequestMapping(method=RequestMethod.GET)
public String showForm(IBean bean){     
    //..
}

@RequestMapping(method=RequestMethod.POST, params={"validate"})
public String validate(@Valid IBean bean, BindingResult result){
    List<ObjectError> errors = bean.validate();
    for(ObjectError e: errors){
        result.addError(e);
    }

    //redirecting, etc
}

}

As you can see, I would instantiate different Beans according to the params and still be using only one method for each GET and POST procedure, because IBean would be an interface that forces all Beans to implement a validate()-method.

I started with Spring only a few days ago, and was wondering if somebody knows a solution to this, who's more experienced than me : )
I searched for an answer but couldn't find a solution to my specific problem. I guess, I could implement a lot of handlers, that are filtered by params, but that would be very redundant, because every method has to do the same (call the validate()-method and add the new errors to the BindingResult)... and I don't think that would be a good solution, tbh.
Hope my question doesn't sound to foolish ^^

Thanks in advance for your time and effort.

Gossip answered 1/6, 2015 at 14:27 Comment(0)
D
0

The Spring way would be to have different @RequestMapping annotated method calling a private method that do the job :

@RequestMapping(method=RequestMethod.POST, params={"validate", "type=bean1"})
public String validate1(@Valid Bean1 bean, BindingResult result){
    return doValidate(bean, result);
}
@RequestMapping(method=RequestMethod.POST, params={"validate", "type=bean2"})
public String validate2(@Valid Bean2 bean, BindingResult result){
    return doValidate(bean, result);
}
private String doValidate(IBean bean, BindingResult result){
    List<ObjectError> errors = bean.validate();
    for(ObjectError e: errors){
        result.addError(e);
    }

    //redirecting, etc
}
Divergency answered 1/6, 2015 at 14:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.