第一種:參數不帶注解
1.直接在controller方法的參數中接受請求參數
此時參數名稱一定要和請求參數的名稱一致,即usename、password要和前端傳過來的參數名一致。
這有個小疑問:前端傳過來的參數名又是什么呢?詳見另一篇博客:web前后端傳值的一些問題
@RequestMapping("/login")
public JsonResult<User> login(String username,String password){
User data = userService.login(username, password);
return new JsonResult<User>(OK,data);
}
【適用於get方式提交,不適用於post方式提交。若"Content-Type"="application/x-www-form-urlencoded",可用post提交】
【url:http://localhost:8080/users/login?username=Tom&password=1234】
2.通過HttpServletRequest接收
-
HttpServletRequest和HttpServletResponse也可以進行參數傳遞。
-
Web服務器收到一個http請求,會針對每個請求創建一個HttpServletRequest和HttpServletResponse對象,向客戶端發送數據找HttpServletResponse,從客戶端取數據找HttpServletRequest
@RequestMapping("/addUser2")
public String addUser2(HttpServletRequest request) {
String username=request.getParameter("username");
String password=request.getParameter("password");
System.out.println("username is:"+username);
System.out.println("password is:"+password);
return "demo/index";
}
【post方式和get方式】
3.多個參數還可以使用java類來接收
@RequestMapping("/addUser3")
public String addUser3(UserModel user) {
System.out.println("username is:"+user.getUsername());
System.out.println("password is:"+user.getPassword());
return "demo/index";
}
注意:類的屬性名稱必須和請求參數名稱一致
第二種:參數帶注解
1.@RequestParam
如果設置了value,test方法中的參數名稱就可以不與請求的參數名稱保持一致,但如果沒有設置value,那么test方法中的參數名稱就必須與請求的參數名稱保持一致。
required的值(boolean)來表示該參數是否必填,false表示非必填。
@RequestParam(defaultValue=xxx)可以設置參數默認值
@RequestMapping("/test")
public String test(@RequestParam String username){
return null;
}
加了這個注解的好處是:
-
當請求參數username不存在時會有異常發生(空指針異常),可以通過設置屬性required=false解決
-
方法參數名可以和前端請求參數名不一致
-
當參數為空時,如果設置了參數默認值,會自動賦值為默認值
@RequestMapping("/test")
public String test(@RequestParam(value="username", required=false) String appName){
return null;
}
@RequestMapping("/test")
public String test(@RequestParam(value="username",required=true,defaultValue="admin") String appName){
return null;
}
【若"Content-Type"="application/x-www-form-urlencoded",post get都可以;若"Content-Type"="application/application/json",只適用get】
2.@PathVariable
路徑變量,接收請求路徑中占位符的值,參數與大括號里的名字一樣要相同
RequestMapping("user/get/mac/{macAddress}")
public String getByMacAddress(@PathVariable String macAddress){
//do something;
}
@PathVariable支持restful風格
3.@ModelAttribute
@RequestMapping(value="/addUser5",method=RequestMethod.POST)
public String addUser5(@ModelAttribute("user") UserModel user) {
System.out.println("username is:"+user.getUsername());
System.out.println("password is:"+user.getPassword());
return "demo/index";
}
@ModelAttribute解釋:運用在參數上,會將客戶端傳遞過來的參數按名稱注入到指定對象中,並且會將這個對象自動加入ModelMap中,便於View層使用
參考鏈接:@ModelAttribute運用詳解
參考鏈接:
https://www.cnblogs.com/lcxdevelop/p/8309018.html
https://blog.csdn.net/weixin_41404773/article/details/80319083
https://blog.csdn.net/u013756192/article/details/79749415?spm=1001.2014.3001.5502
https://blog.csdn.net/JavaNotes/article/details/80722204