1. 常用類注解
@RestController和@Controller是Spring中用于定義控制器的兩個類注解.
1.1?@RestController
@RestController是一個組合類注解,是@Controller和@ResponseBody兩個注解的組合,在使
用?@RestController?注解標記的類中,每個方法的返回值都會以 JSON 或 XML等 的形式直接寫入 HTTP 響應體中,相當于在每個方法上都添加了?@ResponseBody注解.
代碼演示(訪問127.0.0.1:8080/hello/hello1):
@RequestMapping("/hello")
@RestController
public class HelloController {@RequestMapping("/hello1")public String hello() {return "hello spring mvc1";}}
返回的結果如下:
我們可以使用fiddler進行抓包:
可以看到返回的類型是text/html,可以把它看成是一個text或者是html.
1.2 @Controller
@Controller是一個類注解,其主要作用是標記類表示返回的是一個視圖(view).這是用于傳統的SpringMVC架構中的類注解.
代碼演示:
@RequestMapping("/response")
@Controller
public class ResponseController {@RequestMapping("/index")public String index(){return "/index.html";}}
//index.html
<!doctype html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>用戶登錄首頁</title>
</head><body>登錄人: <span id="loginUser"></span><script src="/jquery.min.js"></script><script></script>
</body></html>
這樣就返回了一個html頁面(視圖).
總之,@RestController和@Controller的區別就在于要返回一個視圖(頁面)還是要返回數據.
1.3 @RequestMapping
@RequestMapping表示路由映射,即通過@RequestMapping注解可以達到設置url的目的.在訪問時只有加入@RequestMapping映射的部分,才能成功找到這個路徑.\
代碼演示:
@RequestMapping("/hello")
@RestController
public class HelloController {@RequestMapping("/hello1")public String hello() {return "hello spring mvc1";}
}
我們只有啟動服務器,再訪問127.0.0.1:8080/hello/hello1才能成功接收到后端返回的"hello spring mvc1"這個數據.
?2. 常用方法注解
2.1 @RequestMapping
我們剛才介紹了@RequestMapping是一個類注解,它其實還是一個方法注解,我們在使用方法時需要在方法上也添加上這個注解.同樣表示的是路由映射,影響我們訪問的url.我們再來看一下,其中的屬性:
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
@Reflective({ControllerMappingReflectiveProcessor.class})
public @interface RequestMapping {String name() default "";@AliasFor("path")String[] value() default {};@AliasFor("value")String[] path() default {};RequestMethod[] method() default {};String[] params() default {};String[] headers() default {};String[] consumes() default {};String[] produces() default {};
}
public enum RequestMethod {GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS,TRACE;
}
其中我們主要介紹method這個屬性,method取值于RequestMethod這個枚舉類型,我們使用的最多的就是GET和POST:
@GetMapping("/hello3")public String hello3() {return "hello spring mvc3";}@PostMapping("/hello4")public String hello4() {return "hello spring mvc4";}
報錯信息:Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' is not supported]
POST表示只有使用post請求時才允許進行正確的響應,GET表示get請求時才允許進行正確的響應.如果這個參數不寫,就表示post和get請求都允許.
2.2 @PostMapping
與?@RequestMapping(value = "/hello2",method = RequestMethod.POST)的效果類似,只允許post請求.
2.3 @GetMapping
與?@RequestMapping(value = "/hello2",method = RequestMethod.GET)的效果類似,只允許get請求.
2.4 @RequestParam
這個參數主要有兩個作用.
在前端給后端傳遞參數時,需要規定好參數的名稱,使其保持一致否則將無法成功傳參.例如前端傳給我們的用戶名稱叫做userName,但是后端接收這個參數的名稱叫做name,就無法成功接收.但是我們可以使用@RequestParam這個注解進行參數的綁定,將userName綁定到name上,這樣后端就可以使用name進行操作了.還可以在其中required屬性中設置true/false,表示這個參數是否是必須的.
代碼演示:
@RequestMapping("/param6")public String param6(@RequestParam(value = "userName",required = false)String name,String password){System.out.println("receive userName:"+name+" password:"+ password);return "receive name: "+name+" password:"+ password;}
另外一個主要作用是用來傳遞集合.對于一個簡單的數組來說,我們直接傳遞不會出現任何問題,但是如果我們直接傳遞一個集合,就會發現傳過來的集合是空的.這時,就需要@RequestParam這個注解來將數組綁定到這個集合上,給集合賦值.'
代碼演示:
@RequestMapping("/param8")public String param8(@RequestParam("listParam") List<String> listParam){System.out.println("receive listParam: "+listParam);return "receive listParam: "+listParam;}
2.5 @RequestBody
@RequestBody這個注解主要用來接收對象(傳遞JSON類型的參數),比如我們需要給后端傳遞一個UserInfo對象:
public class UserInfo {public String userName;public String password;public int age;@Overridepublic String toString() {return "UserInfo{" +"userName='" + userName + '\'' +", password='" + password + '\'' +", age=" + age +'}';}
}
我們就需要給出userName,password和age三個參數的值,在傳遞過程中會將這三個參數轉變成JSON格式的數據,只有我們加上@RequestBody這個注解才能成功接收到這個JSON數據,并把它轉換成對象.
代碼演示:
@RequestMapping("/param9")public String param9(@RequestBody UserInfo userInfo){System.out.println("receive userInfo: "+userInfo);return "receive userInfo: "+userInfo;}
2.6 @PathVariable
@PathVariable這個注解用來從url中獲取到參數.比如下述例子,我們要從url中獲取到articlName,我們就可以使用這個注解加上一定的格式進行獲取:
@RequestMapping("/param10/{articlName}")public String param10(@PathVariable("articlName") Integer articlName){System.out.println("receive articlName: "+articlName);return "receive articlName: "+articlName;}
2.7 @RequestPart
@PathVariable這個注解用來進行文件的接收.代碼演示如下:
@RequestMapping("/param12")public String param12(@RequestPart MultipartFile file) throws IOException {System.out.println(file.getName());System.out.println(file.getOriginalFilename());System.out.println(file.getContentType());file.transferTo(new File("D:/temp/"+file1.getOriginalFilename()));return file1.getOriginalFilename();}
2.8 @CookieValue
@CookieValue這個注解用來根據cookie中的鍵獲取對應的值.代碼演示如下:
@RequestMapping("/getCookie2")public String getCookie2(@CookieValue("lzq") String value) {System.out.println(value);System.out.println("get cookies successfully");return "get cookies successfully";}
2.9 @SessionAttribute
@SessionAttribute這個注解用來根據session中的鍵獲取對應的值.代碼演示如下:
@RequestMapping("/getSession3")public String getSession3(@SessionAttribute(value = "name",required = false) String name) {System.out.println("name "+name);System.out.println("get session successfully");return "get session successfully";}
2.10 @RequestHeader
@RequestHeader這個注解用來根據header中的鍵獲取對應的值.代碼演示如下:
@RequestMapping("/getHeader2")public String getHeader2(@RequestHeader("User-Agent") String userAgent) {System.out.println(userAgent);System.out.println("get userAgent successfully");return "get userAgent successfully";}
2.11 @ResponseBody
@ResponseBody是@RestController的一部分,通常用在當@Controller修飾類控制器,而其中某些方法需要返回數據而不是視圖時,代碼演示如下:
@ResponseBody@RequestMapping("/returnData")public String returnData() {System.out.println("returnData");return "returnData";}