开发者

Is there a way to map a Spring 3.0 MVC @RequestParam directly to a Java Bean?

开发者 https://www.devze.com 2023-02-17 21:02 出处:网络
Can this somehow work? do I have to use @InitBinder somehow? public String myActionHandler(ModelMap model, @RequestParam MyPojoBean myBean){

Can this somehow work? do I have to use @InitBinder somehow?

public String myActionHandler(ModelMap model, @RequestParam MyPojoBean myBean){
    ...
}
  1. I'm sure I've seen this somewhere, but I'm not sure where. Is there a开发者_开发问答 simple code example for this?

  2. If the above is possible, how can I catch the exception if the request doesen't match the Bean?


You need to register a custom editor in initBinder:

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(MyPojoBean.class, new MyPojoEditor());
}

class MyPojoEditor extends java.beans.PropertyEditorSupport {
    @Override public String getAsText () {...}
    @Override public void setAsText (String s) {...}
}


You can do this using @InitBinder (see @Abdullah's answer), which is best if you only need to do this for a single class, or using a custom WebArgumentResolver (see this other question), which is more general.

0

精彩评论

暂无评论...
验证码 换一张
取 消