Spring mvc 針對get 和 post 請求引數的不同接收方式
GET 請求
針對與於get請求spring mvc控制層主要接收方式如下
1.直接在controller接收引數,引數名稱要與getURl中傳遞的引數一致
get url : https://localhost:8080/demo/login?&userName=bob&passWord=123
@Controller
public class demo {
@requestMapping(value = "/login" , method=RequestMethod.GET)
public String login(String userName, String passWord) {
//這兩個引數直接可以獲取geturl中的傳遞過來的值
if(("bob").equals userName && ("123").equals(passWord) ) {
return "success";
}
}
}
get url : https://localhost:8080/demo/login?&userName=joe
2.使用 request.getQueryString() 獲取spring MVC get請求的引數
@requestMapping(value="/addUser" , method=RequestMethod.GET)
public String addUser(HttpServletRequest request) {
//userName="joe"
String userName = request.getQueryString();
}
3.使用HttpServletRequest 接收(注意,該方法Post請求也同樣試用)
@requestMapping(value="/addUser" , method=RequestMethod.GET)
public String addUser(HttpServletRequest request) {
//userName="joe"
String userName = request.getParamter("userName");
String pass = request.getParamter("passWord");
}
4.過一個bean來接收(注意,該方法Post請求也同樣試用)
@requestMapping(value="/addUser" , method=RequestMethod.GET)
public String addUser(UserEntity user) {
String userName = user.getUserName();
String passWord = user.getPassWord();
}
5.用註解@RequestParam繫結請求引數到方法入參 當請求引數username不存在時會有異常發生,可以通過設定屬性required=false解決,例如: @RequestParam(value="username", required=false)
(重要注意
若"Content-Type"="application/application/json",只適用get
若"Content-Type"="application/x-www-form-urlencoded",post get都可以
)
@RequestMapping(value="/addUser",method=RequestMethod.GET) public String addUser6(@RequestParam("userName") String username,@RequestParam("passWord") String password) { System.out.println("username is:"+username); System.out.println("password is:"+password); return "demo/index"; }
POST請求
1.、使用@ModelAttribute註解獲取POST請求的FORM表單資料
/** * 4、使用@ModelAttribute註解獲取POST請求的FORM表單資料 * @param user * @return */ @RequestMapping(value="/addUser",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"; }2.get請求方式3
3.get請求方式4
4.get請求方式5