簡體   English   中英

在Spring中將路徑變量綁定到自定義模型對象

[英]Bind Path variables to a custom model object in spring

我有一個模擬我的請求的類,比如

class Venue {
    private String city;
    private string place;

    // Respective getters and setters.
}

我想支持一個RESTful URL來獲取有關場地的信息。 所以我有這樣的控制器方法。

@RequestMapping(value = "/venue/{city}/{place}", method = "GET")
public String getVenueDetails(@PathVariable("city") String city, @PathVariable("place") String place, Model model) {
    // code
}

有沒有辦法,我可以說在春天將我的路徑變量綁定到模型對象(在本例中為Venue)而不是獲取每個單獨的參數?

Spring MVC提供了將請求參數和路徑變量綁定到JavaBean的功能,在您的情況下,它是Venue 例如:

@RequestMapping(value = "/venue/{city}/{place}", method = "GET")
public String getVenueDetails(Venue venue, Model model) {
    // venue object will be automatically populated with city and place
}

請注意,您的JavaBean必須具有cityplace屬性才能工作。

有關更多信息,您可以查看spring-projects / spring-mvc-showcase中的withParamGroup()示例

根據http://static.springsource.org/spring/docs/3.2.3.RELEASE/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-uri-templates上提供的Spring文檔,自動僅為簡單類型提供支持:

@PathVariable參數可以是任何簡單類型,如int,long,Date等。如果無法執行此操作,Spring會自動轉換為適當的類型或拋出TypeMismatchException。

我沒有嘗試過@RequestParamModel這種特定組合,但看起來您可以通過創建自定義WebBindingInitializer來實現所需的實現,詳見http://static.springsource.org/spring/docs/3.2.3 .RELEASE / spring-framework-reference / html / mvc.html#mvc-ann-typeconversion

自定義類將具有對WebRequest的訪問權限,並將返回填充了從此請求中提取的數據的域對象。

您可以提供HandlerMethodArgumentResolver接口的實現。 這個接口主要用於以Spring無法解決的方式解析控制器方法的參數(這實際上就是你要做的)。 您通過實現以下兩種方法來實現此目的:

public boolean supportsParameter(MethodParameter mp) {
    ...
}

public Object resolveArgument(mp, mavc, nwr, wdbf) throws Exception {
    ...
}

您可以通過以下方式將實現注入Spring上下文:

<mvc:annotation-driven>
    <mvc:argument-resolvers>
        <bean class="com.path.ImplementationOfHandlerMethodArgumentResolver"/>
    </mvc:argument-resolvers>
</mvc:annotation-driven>

當Spring遇到無法解析的參數時,它會調用你的方法supportsParameter()來查看你的解析器是否可以解析參數。 如果您的方法返回true,那么Spring將調用您的resolveArgument()方法來實際解析參數。 在此方法中,您可以訪問NativeWebRequest對象,您可以使用該對象來獲取contextPath之外的路徑。 (在您的情況下,它將是: /venue/{city}/{place} )您可以解析請求路徑並嘗試在您的Venue對象中填充城市/地點字符串。

暫無
暫無

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

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