簡體   English   中英

抽象類和Spring MVC @ ModelAttribute / @ RequestParam

[英]Abstract classes and Spring MVC @ModelAttribute/@RequestParam

我的Spring / Hibernate應用程序中具有模型類的層次結構。

當向Spring MVC控制器提交POST表單時,是否有任何標准方法指定要提交的對象的類型,因此Spring可以實例化在接收方法的@ModelAttribute或@RequestParam中聲明的類型的正確子類?

例如:

public abstract class Product {...}
public class Album extends Product {...}
public class Single extends Product {...}


//Meanwhile, in the controller...
@RequestMapping("/submit.html")
public ModelAndView addProduct(@ModelAttribute("product") @Valid Product product, BindingResult bindingResult, Model model)
{
...//Do stuff, and get either an Album or Single
}

Jackson可以使用@JsonTypeInfo批注將JSON反序列化為特定的子類型。 我希望Spring可以做同樣的事情。

Jackson可以使用@JsonTypeInfo批注將JSON反序列化為特定的子類型。 我希望Spring可以做同樣的事情。

假設您使用Jackson進行類型轉換(如果Spring在類路徑中找到它並且在XML中包含<mvc:annotation-driven/> ,則Spring將自動使用Jackson),那么它與Spring無關。 注釋類型,Jackson將實例化正確的類。 不過,您將必須在Spring MVC控制器方法中執行instanceof檢查。

評論后更新:

看一下15.3.2.12定制WebDataBinder初始化 您可以使用@InitBinder方法,該方法根據請求參數注冊編輯器:

@InitBinder
public void initBinder(WebDataBinder binder, HttpServletRequest request) {
    String productType = request.getParam("type");

    PropertyEditor productEditor;
    if("album".equalsIgnoreCase(productType)) {
        productEditor = new AlbumEditor();
    } else if("album".equalsIgnoreCase(productType))
        productEditor = new SingleEditor();
    } else {
        throw SomeNastyException();
    }
    binder.registerCustomEditor(Product.class, productEditor);
}

暫無
暫無

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

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