簡體   English   中英

有沒有一種方法可以將Spring 3.0 MVC @RequestParam直接映射到Java Bean?

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

這可以以某種方式工作嗎? 我必須以某種方式使用@InitBinder嗎?

public String myActionHandler(ModelMap model, @RequestParam MyPojoBean myBean){
    ...
}
  1. 我敢肯定我在某個地方見過,但是我不確定在哪里。 是否有一個簡單的代碼示例?

  2. 如果以上情況可行,如果請求與Bean不匹配,如何捕獲異常?

您需要在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) {...}
}

您可以使用@InitBinder (請參見@InitBinder的答案)來執行此操作,如果只需要針對單個類執行此操作,或者使用更通用的自定義WebArgumentResolver (請參見此其他問題 ),則最好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM