Spring 注解之@PathVariable


@PathVariable只支持一個屬性value,類型是為String,代表綁定的屬性名稱。默認不傳遞時,綁定為同名的形參。 

用來便捷地提取URL中的動態參數。其英文注釋如下:

Annotation which indicates that a method parameter should be bound to a URI template variable. Supported for {@link RequestMapping} annotated handler methods in Servlet environments.

應用時,在@RequestMapping請求路徑中,將需要傳遞的參數用花括號{}括起來,然后,通過@PathVariable("參數名稱")獲取URL中對應的參數值。如果@PathVariable標明參數名稱,則參數名稱必須和URL中參數名稱一致。

@RequestMapping("/viewUser/{id}/{name}")
    public Map<String, Object> viewUser(@PathVariable("id") Integer idInt, @PathVariable Integer name) {
        System.out.println("@PathVariable中 請求參數 id = " + idInt);
        Map<String, Object> user = new HashMap<>();
        user.put("id", idInt);
        user.put("name", name);
        return user;
    }
    /**
     * @Title viewUser2
     * @Description @PathVariable未標注參數名稱,則被注解參數名必須后URL中的一致
     * @date 2018-12-15 11:08
     */
    @RequestMapping("/owners/{ownerId}")
    public Map<String, Object> viewUser2(@PathVariable Integer ownerId) {
        System.out.println("@PathVariable中 請求參數 ownerId = " + ownerId);
        Map<String, Object> user = new HashMap<>();
        user.put("id", ownerId);
        user.put("name", "Lucy");
        return user;
    }

URI 模板 “/owners/{ownerId}” 指定了一個名叫 ownerId的變量。當控制器處理這個請求時,ownerId的值被設置為從 URI 中解析出來。比如,當請求 /viewUser/100 進來時,100 就是 ownerId的值。 

參考文獻:https://docs.spring.io/spring/docs/5.0.0.M1/spring-framework-reference/htmlsingle/#mvc-ann-requestmapping-uri-templates

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM