更新時間:2022-07-25 09:44:49 來源:動力節(jié)點 瀏覽2027次
URL形式:
? http://localhost:8080/test/one 表單提交數(shù)據(jù),其中屬性名與接收參數(shù)的名字一致;
? http://localhost:8080/test/one?name=aaa 數(shù)據(jù)顯示傳送
注意:delete請求用表單提交的數(shù)據(jù)后臺無法獲取,得將參數(shù)顯示傳送;
controller端的代碼
@RequestMapping("/one")
public String testOne(String name){
System.out.println(name);
return "success";
}
說明:直接將屬性名和類型定義在方法的參數(shù)中,前提是參數(shù)名字必須得跟請求發(fā)送的數(shù)據(jù)的屬性的名字一致,而且這種方式讓請求的參數(shù)可為空,請求中沒有參數(shù)就為null;
URL形式:
http://localhost:8080/test/two 表單提交數(shù)據(jù),其中屬性名與接收的bean內(nèi)的屬性名一致;
http://localhost:8080/test/two?username=aa&password=bb 數(shù)據(jù)顯示傳送
構(gòu)建一個Userbean
public class Test {
private String username;
private String password;
}
get,set,tostring沒貼上來
后端請求處理代碼
@RequestMapping("/two")
public String testTwo(User user){
System.out.println(user.toString());
return "success";
}
說明:User類中一定要有set,get方法,springmvc會自動將與User類中屬性名一致的數(shù)據(jù)注入User中,沒有的就不注入;
URL形式:
? http://localhost:8080/test/three 采用表單提交數(shù)據(jù)
? http://localhost:8080/test/three?username=aa 數(shù)據(jù)顯示傳送
后端請求處理代碼:
@RequestMapping("/three")
public String testThree(HttpServletRequest request){
String username = request.getParameter("username");
System.out.println(username);
return "success";
}
說明:后端采用servlet的方式來獲取數(shù)據(jù),但是都用上框架了,應(yīng)該很少用這種方式來獲取數(shù)據(jù)了吧;
URL形式
http://localhost:8080/test/four/aaa/bbb
后端請求處理代碼:
@RequestMapping("/four/{username}/{password}")
public String testFour(
@PathVariable("username")String username,
@PathVariable("password")String password
){
System.out.println(username);
System.out.println(password);
return "success";
}
說明:@PathVariable注解會將請求路徑中對應(yīng)的數(shù)據(jù)注入到參數(shù)中
注意:@PathVariable注解的數(shù)據(jù)默認不能為空,就是請求路徑中必須帶有參數(shù),不能為空,如果請求數(shù)據(jù)為空,則需要在@PathVariable中將required屬性改為false;
URL形式
http://localhost:8080/test/five 表單提交數(shù)據(jù),未顯示傳送
http://localhost:8080/test/two?username=aa&password=bb 數(shù)據(jù)顯示傳送
后端處理代碼
@RequestMapping("/five")
public String testFive(@RequestParam(value = "username")String username,
@RequestParam("password")String password
){
System.out.println(username);
System.out.println(password);
return "success";
}
說明: @RequestParam會將請求中相對應(yīng)的數(shù)據(jù)注入到參數(shù)中。
注意: @RequestParam注解的參數(shù)也是不能為空的,如果需要為空,則需要將required屬性改為false,還有就是 @RequestParam注解中的defaultValue 屬性可以為參數(shù)設(shè)置默認值。