SpringMVC 註解 @RequestParam、@PathVariable、@RequestBody

目錄

@SuppressWarnings 取消警告

@RequestParam 請求參數

@PathVariable 路徑變量

@RequestBody 請求正文參數


@SuppressWarnings 取消警告

1、java.lang.SuppressWarnings 註解主要用在取消一些編譯器產生的警告對代碼左側行列的遮擋,比如這會擋住斷點調試時打的斷點。

2、通過源碼可知 @SuppressWarnings 其註解目標爲類、字段、構造函數、方法、方法參數、方法內的局部變量。

3、@SuppressWarnings("value1","values2"...),其中的 value 取值如下:

關鍵字 用途
all to suppress all warnings (抑制所有警告)
boxing to suppress warnings relative to boxing/unboxing operations (抑制裝箱、拆箱操作時候的警告)
cast to suppress warnings relative to cast operations (抑制映射相關的警告)
dep-ann to suppress warnings relative to deprecated annotation (抑制啓用註釋的警告)
deprecation to suppress warnings relative to deprecation (抑制過期方法警告)
fallthrough to suppress warnings relative to missing breaks in switch statements (抑制確在switch中缺失breaks的警告)
finally to suppress warnings relative to finally block that don’t return (抑制finally模塊沒有返回的警告)
hiding to suppress warnings relative to locals that hide variable(抑制相對於隱藏變量的局部變量的警告)
incomplete-switch to suppress warnings relative to missing entries in a switch statement (enum case)(忽略沒有完整的switch語句)
nls to suppress warnings relative to non-nls string literals( 忽略非nls格式的字符)
null to suppress warnings relative to null analysis( 忽略對null的操作)
rawtypes to suppress warnings relative to un-specific types when using generics on class params( 使用generics時忽略沒有指定相應的類型)
restriction to suppress warnings relative to usage of discouraged or forbidden references( 抑制禁止使用勸阻或禁止引用的警告)
serial to suppress warnings relative to missing serialVersionUID field for a serializable class( 忽略在serializable類中沒有聲明serialVersionUID變量)
static-access to suppress warnings relative to incorrect static access( 抑制不正確的靜態訪問方式警告)
synthetic-access to suppress warnings relative to unoptimized access from inner classes( 抑制子類沒有按最優方法訪問內部類的警告)
unchecked to suppress warnings relative to unchecked operations( 抑制沒有進行類型檢查操作的警告)
unqualified-field-access to suppress warnings relative to field access unqualified( 抑制沒有權限訪問的域的警告)
unused to suppress warnings relative to unused code( 抑制沒被使用過的代碼的警告)
    @SuppressWarnings({"unused", "unchecked"})
    public void show() {
        Date inco_date = new Date();// 到賬日期
        String inco_date_str = DateFormatUtils.format(inco_date, "yyyy-MM-dd HH:mm:ss");
    }

@RequestParam 請求參數

1、org.springframework.web.bind.annotation.RequestParam 註解將瀏覽器請求參數綁定至控制層方法參數上。

2、@RequestParam 三個常用屬性:

(1)value:請求參數名(必須配置)

(2)required:是否必需,默認爲 true,即請求中必須包含該參數,如果沒有包含,將會拋出異常(可選配置)

(3)defaultValue:當沒有傳入參數時,則使用此默認值。如果設置了該值,required 將自動設爲 false,無論是否配置了required,配置了什麼值,都是 false(可選配置)

    /**
     * required 屬性默認爲 true,此時頁面必須傳入 uid 參數,否則報 400 錯誤
     *
     * @param uid value 屬性的值與參數名稱要相同
     * @return
     */
    @GetMapping("get1")
    public String get1(@RequestParam(value = "uid") Integer uid) {
        logger.info("get = >" + uid);
        return "get = >" + uid;
    }

    /**
     * required = false:此時頁面可以不傳入 uid 參數時,後臺 uid 爲 null
     *
     * @param uid :value 屬性的值與參數名稱要相同
     * @return
     */
    @GetMapping("get2")
    public String get2(@RequestParam(value = "uid", required = false) Integer uid) {
        logger.info("get = >" + uid);
        return "get = >" + uid;
    }

    /**
     * 此時頁面沒有傳入 uid 參數時,將使用默認值 9527
     *
     * @param uid :value 屬性的值與參數名稱要相同
     * @return
     */
    @GetMapping("get3")
    public String get3(@RequestParam(value = "uid", defaultValue = "9527") Integer uid) {
        logger.info("get = >" + uid);
        return "get = >" + uid;
    }

    /**
     * 平時這種方法寫的最多,當頁面沒有傳入 uid 參數時,後臺 uid 此時默認爲 null
     *
     * @param uid
     * @return
     */
    @GetMapping("get4")
    public String get4(Integer uid) {
        logger.info("get = >" + uid);
        return "get = >" + uid;
    }

@PathVariable 路徑變量

1、帶佔位符的 URL 是 Spring3.0 新增的功能,通過 @PathVariable 可以將 URL 中佔位符參數綁定到控制器處理方法的入參中。

2、URL 中的 {xxx} 佔位符可以通過 @PathVariable("xxx") 綁定到操作方法的入參中。

3、如有 url 地址: http://localhost:8080/find/1/china/2?id=100&name=zhangSan。則 @RequestParam 可以用來獲取 "?" 後面的 id、name 參數,而 @PathVariable 則是獲取 url 中的參數,如裏面的 "1"、"china"、"2"

4、 @PathVariable 有兩個常用屬性 value 與 required,value 用於指定 url 中的佔位符名稱,required 表示佔位符參數是否必須。

5、required 注意 事項:

如果 required = false,而用戶沒有傳這個參數,那麼它會去找這個參數去掉之後的替代 url,如果發現有替代的url,就可以處理這個請求,如果沒有找到,則頁面報錯 404

帶佔位符的 url 優先級高於其它沒有佔位符的 url 地址。

如果 required = true,則帶佔位符的 url 必須匹配,即使還有其它的 url 匹配未傳入參數的地址,同樣會報錯 404

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.logging.Logger;
@RestController
public class WmxController {
    /**
     * @PathVariable : 其中的 value 屬性值對應 url 中的佔位符名稱,只有 value 時,可以省略 value 不寫,甚至直接括弧不寫
     * <p>
     * http://localhost:8080/wmx/movie/1/2/3 :正確
     * http://localhost:8080/wmx/movie/1/2/3/:正確
     * http://localhost:8080/wmx/movie/1/2/3/4:報錯 404
     * http://localhost:8080/wmx/movie/1/2/ :報錯 404,注意 1/2/ 與 1/2/3 是不同的 url
     * http://localhost:8080/wmx/movie/1/2 :報錯 404
     */
    @GetMapping("/wmx/movie/{type}/{region}/{order}")
    public String findMovie1(@PathVariable(value = "type") Integer type,//三個 type 對應
                             @PathVariable("region") String region,//省略 value
                             @PathVariable Integer order) {//直接省略括號,最簡形式

        Logger logger = Logger.getAnonymousLogger();
        logger.info("type=" + type + ", region=" + region + ", order=" + order);
        return "type=" + type + ", region=" + region + ", order=" + order;
    }

    /**
     * post 請求與 get 請求一樣
     * http://localhost:8080/wmx/movie2/1/china/2 :正確
     * http://localhost:8080/wmx/movie2/1/china/:報錯 404,與上面是兩個不同的 url
     * http://localhost:8080/wmx/movie2/china/2 :報錯 404
     *
     * @return
     */
    @PostMapping("/wmx/movie2/{type}/china/{order}")
    public String findMovie2(@PathVariable Integer type, @PathVariable Integer order) {
        Logger logger = Logger.getAnonymousLogger();
        logger.info("type=" + type + ", order=" + order);
        return "type=" + type + ", order=" + order;
    }

    /**
     * "/wmx/movie3/{id}"
     * 首先明白 :/wmx/movie3/ 與 /wmx/movie3 是相同的 url ,但與 /wmx/movie3/20  是不同的 url
     * required 屬性:表示 url 中的參數是否可以爲 null,默認爲 true
     * 如下所示 當沒有設置 required = false 時,則此方法的路徑必須滿足 "/wmx/movie3/{id}" 的格式,否則就是 404 錯誤
     * 設置 required = false 後,則 "/wmx/movie3/{id}" 中的參數 id 可以爲 null,此時就會去匹配沒有 id 時的格式,如 "/wmx/movie3"
     * XxxMapping 可以設置多個 url 地址,當然其中的 "/wmx/movie3" 也可以在其它方法中,並不一定要在同一個方法中
     *
     * @param id
     * @return
     */
    @GetMapping(value = {"/wmx/movie3", "/wmx/movie3/{id}"})
    public String findMovie3(@PathVariable(required = false) Integer id) {
        Logger logger = Logger.getAnonymousLogger();
        logger.info("id=" + id);
        return "id=" + id;
    }
}

@RequestBody 請求正文參數

請參考《@RequestBody 接收數組、List 參數》

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章