Spring MVC|常用註解介紹

@RequestMapping

源碼:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
}

作用:
  用來建立請求 URL 與和處理方法之間的對應關係。
出現位置:
  類上:
    請求 URL 的第一級訪問目錄。此處不寫的話,就相當於應用的根目錄。寫的話需要以/開頭。它出現的目的是爲了使我們的 URL 可以按照模塊化管理:
    例如:
      用戶模塊:
        /user/add
        /user/update
        /user/delete
      加粗的部分就要使用@RequestMapping註解來配置,使我們的 URL 更加精細。
  方法上:
    請求 URL 的第二級訪問目錄。
屬性:
    value:用於指定請求的 URL。它和 path 屬性的作用是一樣的。
    method:用於指定請求的方法。
        類型:RequestMethod[ ](RequestMethod是一個枚舉類)
        取值:RequestMethod + . + GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE任意一種請求方法。
    params:用於指定限制請求參數的條件。它支持簡單的表達式。要求請求參數的 key 和 value 必須滿足配置的要求。
        類型:String[ ]
        例如:
          params = {“username”},表示請求參數中必須要有 username 。
          params = {"!sex"},表示請求參數中不能有 sex 。
          params = {“age=22”},表示請求參數中必須要有 age 的值必須爲 22 。
          params = {“money!=100”},表示請求參數中必須要有 money 的值不能爲 100 。
    headers:用於指定限制請求消息頭的條件。它的限制規則與 params 屬性一樣。


@RequestParam

源碼:

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestParam {

作用:
  把請求中指定名稱的參數賦值給控制器中方法的形參。
屬性:
    value:用於將請求參數和形參綁定。和 name 屬性作用一樣。
    required:表示請求中是否必須提供 value 中所指定的請求參數。默認值:true 。表示必須提供,如果不提供將報錯。


@RequestBody

源碼:

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestBody {
}

作用:
  用於獲取請求體內容。get 方式沒有請求體,所以不適用。
屬性:
    required:表示必須有請求體。默認值是:true 。當取值是 true 時,get 請求方式會報錯。如果取值爲 false,get 請求得到的是 null 。


@PathVaribale

源碼:

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PathVariable {
}

作用:
  用於綁定url中的佔位符。例如:請求 URL 中 /delete/{id},這個{id}就是 URL 佔位符。
  URL 支持佔位符是 spring3.0 之後加入的。是 springmvc 支持 rest 風格 URL 的一個重要標誌。關於 rest 風格,點擊這裏瞭解。
屬性:
    value:用於指定 URL 中佔位符名稱。
    required:是否必須提供佔位符。
示例:

@RequestMapping("/pathVariable/{id}")
    public String testPathVariable(@PathVariable("id") Integer uid) {
        System.out.println(uid);
    }

@RequestHeader

源碼:

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestHeader {
}

作用:
  用於獲取請求消息頭。
屬性:
    value:提供消息頭名稱。和 name 屬性作用一樣。
    required:是否必須有此消息頭。


@CookieValue

源碼:

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CookieValue {
}

作用:
  用於把指定 cookie 名稱的值傳入控制器方法參數。
屬性:
    value:value:指定 cookie 的名稱。和 name 屬性作用一樣。
    required:是否必須有此 cookie 。


@ModelAttribute

源碼:

@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ModelAttribute {
}

作用:
  該註解是 SpringMVC4.3 版本以後新加入的。它可以用於修飾方法和參數。
出現位置:
  方法上:
    出現在方法上,表示當前方法會在控制器的方法執行之前,先執行。它可以修飾沒有返回值的方法,也可以修飾有具體返回值的方法。
  參數上:
    出現在參數上,獲取指定的數據給參數賦值。

屬性:
    value:用於獲取數據的 key。key 可以是 POJO 的屬性名稱,也可以是 map 結構的 key 。
應用場景:
  當表單提交數據不是完整的實體類數據時,保證沒有提交數據的字段使用數據庫對象原來的數據。
  例如:
    我們在編輯一個用戶時,用戶有一個創建信息字段,該字段的值是不允許被修改的。在提交表單數據是肯定沒有此字段的內容,一旦更新會把該字段內容置爲 null ,此時就可以使用此註解解決問題。


@SessionAttributes

源碼:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface SessionAttributes {
}

作用:
  用於多次執行控制器方法間的參數共享。
屬性:
    value:用於指定存入的屬性名稱。
    type:用於指定存入的數據類型。



@ModelAttribute使用示例

作用一: 作用在方法上,則此方法在所有控制器方法之前執行。
Jsp代碼:

<a href="${pageContext.request.contextPath}/testModelAttribute1">測試</a>

Controller代碼:

    @ModelAttribute
    public void before() {
        System.out.println("before方法執行了");
    }

    @RequestMapping("/testModelAttribute1")
    public String testModelAttribute1() {
        System.out.println("testModelAttribute1方法執行了");
        return null;
    }

輸出:

before方法執行了
testModelAttribute1方法執行了

作用二: 案例準備:用戶註冊後信息(username,password,birthday)存於數據庫中,當執行更新操作時,因爲某一字段(birthday)我們設置不允許用戶修改,沒有將數據庫中 birthday 字段發送給前端,導致用戶更新提交後,前端傳過來的birthday字段內容爲 null ,如果直接將請求參數封裝到實體類中,然後持久化,肯定會造成 birthday 字段的數據丟失。@ModelAttribute 註解可以解決這個問題。
Jsp代碼:

<form method="post" action="${pageContext.request.contextPath}/testModelAttribute2">
    <input type="text" name="username"/>
    <input type="text" name="password"/>
    <input type="submit" value="提交"/>
</form>

實現方式一:@ModelAttribute修飾的方法帶有返回值。
Controller代碼:

    @ModelAttribute
    public User before(String username) {
        //首先根據請求參數username查詢數據庫,將數據庫中的信息封裝到user中
        User user = userService.findByUsername(username);
        return user;//返回user,供testModelAttribute2方法使用
    }

    @RequestMapping("/testModelAttribute1")
    //定義一個User類型變量接收before方法返回的對象,同時
    //spring mvc會根據請求中某些參數的有無來決定覆蓋掉User對象中的哪些屬性。
    public String testModelAttribute2(User user) {
        System.out.println("testModelAttribute2方法執行了" + user);
        return null;
    }

實現方式二:@ModelAttribute修飾的方法不帶返回值。
Controller代碼:

    @ModelAttribute
    //需要定義Map類型的形參,用於存放從數據庫中查詢得到的user對象
    public void before(String username, Map<String,User> map) {
        User user = userService.findByUsername(username);
        map.put("u", user);
    }

    @RequestMapping("/testModelAttribute1")
    //@ModelAttribute註解作用於參數上,指定 map 中的 key 來接收 User對象
    public String testModelAttribute2(@ModelAttribute("u") User user) {
        System.out.println("testModelAttribute2方法執行了" + user);
        return null;
    }

@SessionAttributes使用示例

作用: 多個控制方法間數據共享。案例準備:三個功能,用戶點擊登錄,將登錄信息存入session。用戶進行更新操作,首先要判斷用戶是否登錄,根據判斷結果跳轉到更新頁面或者登錄頁面。用戶登出。
Jsp代碼:

<form method="post" action="${pageContext.request.contextPath}/login">
    <input type="text" name="username"/>
    <input type="text" name="password"/>
    <input type="submit" value="提交"/>
</form>
<a href="${pageContext.request.contextPath}/update">更新</a>
<a href="${pageContext.request.contextPath}/loginOut">登出</a>

Controller代碼:

@Controller
//把request域對象中key爲"u"的對象存入session
@SessionAttributes("u")
public class FirstController {

    /**
     * 登錄
     * @param user
     * @param model
     * @return
     * Model 是 spring 提供的一個接口,該接口有一個實現類 ExtendedModelMap
     * 該類繼承了 ModelMap ,而 ModelMap 是 LinkedHashMap 子類。
     */
    @RequestMapping("/login")
    public String login(User user, Model model) {
        //底層會把user存入request域對象中
        model.addAttribute("u", user);
        return "index";
    }

    /**
     * 更新
     * @param modelMap
     * @return
     */
    @RequestMapping("/update")
    public String update(ModelMap modelMap) {
        //從session中取出user對象
        User u = (User) modelMap.get("u");
        System.out.println(u);
        return u != null ? "update" : "login";
    }

    /**
     * 登出
     * @param sessionStatus
     */
    @RequestMapping("/loginOut")
    public void loginOut(SessionStatus sessionStatus) {
        //銷燬session
        sessionStatus.setComplete();
        System.out.println("用戶登出,session被銷燬");
    }
}
發佈了46 篇原創文章 · 獲贊 1 · 訪問量 2507
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章