Spring MVC常用註解,你會幾個?

茅坤寶駿氹發表於2018-05-04

轉載自 Spring MVC常用註解,你會幾個?


常用註解

  • Controller

註解一個類表示控制器,Spring MVC會自動掃描標註了這個註解的類。

  • RequestMapping

請求路徑對映,可以標註類,也可以是方法,可以指定請求型別,預設不指定為全部接收。

  • RequestParam

放在引數前,表示只能接收引數a=b格式的資料,即 Content-Typeapplication/x-www-form-urlencoded型別的內容。

  • RequestBody

放在引數前,表示引數從request body中獲取,而不是從位址列獲取,所以這肯定是接收一個POST請求的非a=b格式的資料,即 Content-Type不為 application/x-www-form-urlencoded型別的內容。

  • ResponseBody

放在方法上或者返回型別前,表示此方法返回的資料放在response body裡面,而不是跳轉頁面。一般用於ajax請求,返回json資料。

  • RestController

這個是Controller和ResponseBody的組合註解,表示@Controller標識的類裡面的所有返回引數都放在response body裡面。

  • PathVariable

路徑繫結變數,用於繫結restful路徑上的變數。

  • @RequestHeader

放在方法引數前,用來獲取request header中的引數值。

  • @CookieValue;

放在方法引數前,用來獲取request header cookie中的引數值。

  • GetMapping PostMapping PutMapping.. *Mapping的是Spring4.3加入的新註解,表示特定的請求型別路徑對映,而不需要寫RequestMethod來指定請求型別。

演示

import org.dom4j.util.UserDataElement;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/test")
public class TestController {

    @RequestMapping(value = "/get/{no}", method = RequestMethod.GET)
    @ResponseBody
    public Object get(@PathVariable("no") String no) {
        return new UserDataElement("");
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public void save(@RequestBody UserDataElement user) {

    }

}


相關文章