Controller中獲取輸入參數注解使用總結


1.處理request的uri部分的參數(即restful訪問方式):@PathVariable.

當使用restful訪問方式時, 即 someUrl/{paramId}, 這時的參數可通過 @Pathvariable注解來獲取。

調用方式(get方法):http://localhost:4005/***/cxhdlb/111111

接收參數代碼:

 

@RequestMapping(value = "/cxhdlb/{param}", method = RequestMethod.GET)
    public List<String> findEventList(@PathVariable String param) {
        System.out.println(param);
}

 

2.處理request header部分的參數:@RequestHeader,@CookieValue

@RequestHeader 注解,可以把Request請求header部分的值綁定到方法的參數上。

這是一個Request 的header部分:

復制代碼
Host                    localhost:8080
Accept                  text/html,application/xhtml+xml,application/xml;q=0.9
Accept-Language         fr,en-gb;q=0.7,en;q=0.3
Accept-Encoding         gzip,deflate
Accept-Charset          ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive              300
復制代碼

接收參數代碼:

復制代碼
  復制代碼
@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
                              @RequestHeader("Keep-Alive") long keepAlive)  {
          //...
}
復制代碼 
復制代碼

上面的代碼,把request header部分的 Accept-Encoding的值,綁定到參數encoding上了, Keep-Alive header的值綁定到參數keepAlive上。 

@CookieValue 可以把Request header中關於cookie的值綁定到方法的參數上。

例如有如下Cookie值:

JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84

接收參數代碼:

復制代碼
@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@CookieValue("JSESSIONID") String cookie)  {

  //...

}
復制代碼

即把JSESSIONID的值綁定到參數cookie上。

 

3.處理request body部分的注解:@RequestParam,@RequestBody,@Validated

@RequestParam注解用來接收地址中的參數,參數的格式是http://*****?uid=111111&uname=張三。

接收參數代碼:

復制代碼
@Controller
@RequestMapping("/users")
public class UserController{
    @RequestMapping(value = "/hqyhxx",method = RequestMethod.GET)
    public String getUserInfo(@RequestParam("uid") String uid,@RequestParam("uname") String uname) {
    //...
  }
}
復制代碼

@Validated注解可以用一個模型來接收地址欄中的參數,參數的格式是http://*****?uid=111111&uname=張三。

接收參數代碼:

復制代碼
@Controller
@RequestMapping("/users")
public class UserController{
    @RequestMapping(value = "/hqyhxx",method = RequestMethod.GET)
    public String getUserInfo(@Validated User user) {
         String uid = user.getUid();
      String uname = user.getUname(); } }
復制代碼

@RequestBody注解用來接收request的body中的參數。

接收參數代碼:

@RequestMapping(value = "/cjhd", method = RequestMethod.POST)
    public Result createEvent(@RequestBody ParameterModel parameterModel, HttpServletRequest request,
            HttpServletResponse response) {
     String rowkey = parameterModel.getRowkey();
}

 


免責聲明!

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



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