更新時(shí)間:2022-07-25 09:44:49 來源:動(dòng)力節(jié)點(diǎn) 瀏覽1754次
URL形式:
? http://localhost:8080/test/one 表單提交數(shù)據(jù),其中屬性名與接收參數(shù)的名字一致;
? http://localhost:8080/test/one?name=aaa 數(shù)據(jù)顯示傳送
注意:delete請(qǐng)求用表單提交的數(shù)據(jù)后臺(tái)無法獲取,得將參數(shù)顯示傳送;
controller端的代碼
@RequestMapping("/one")
public String testOne(String name){
System.out.println(name);
return "success";
}
說明:直接將屬性名和類型定義在方法的參數(shù)中,前提是參數(shù)名字必須得跟請(qǐng)求發(fā)送的數(shù)據(jù)的屬性的名字一致,而且這種方式讓請(qǐng)求的參數(shù)可為空,請(qǐng)求中沒有參數(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)建一個(gè)Userbean
public class Test {
private String username;
private String password;
}
get,set,tostring沒貼上來
后端請(qǐng)求處理代碼
@RequestMapping("/two")
public String testTwo(User user){
System.out.println(user.toString());
return "success";
}
說明:User類中一定要有set,get方法,springmvc會(huì)自動(dòng)將與User類中屬性名一致的數(shù)據(jù)注入U(xiǎn)ser中,沒有的就不注入;
URL形式:
? http://localhost:8080/test/three 采用表單提交數(shù)據(jù)
? http://localhost:8080/test/three?username=aa 數(shù)據(jù)顯示傳送
后端請(qǐng)求處理代碼:
@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
后端請(qǐng)求處理代碼:
@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注解會(huì)將請(qǐng)求路徑中對(duì)應(yīng)的數(shù)據(jù)注入到參數(shù)中
注意:@PathVariable注解的數(shù)據(jù)默認(rèn)不能為空,就是請(qǐng)求路徑中必須帶有參數(shù),不能為空,如果請(qǐng)求數(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會(huì)將請(qǐng)求中相對(duì)應(yīng)的數(shù)據(jù)注入到參數(shù)中。
注意: @RequestParam注解的參數(shù)也是不能為空的,如果需要為空,則需要將required屬性改為false,還有就是 @RequestParam注解中的defaultValue 屬性可以為參數(shù)設(shè)置默認(rèn)值。
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)