更新時間:2022-07-25 09:44:49 來源:動力節點 瀏覽1607次
URL形式:
? http://localhost:8080/test/one 表單提交數據,其中屬性名與接收參數的名字一致;
? http://localhost:8080/test/one?name=aaa 數據顯示傳送
注意:delete請求用表單提交的數據后臺無法獲取,得將參數顯示傳送;
controller端的代碼
@RequestMapping("/one")
public String testOne(String name){
System.out.println(name);
return "success";
}
說明:直接將屬性名和類型定義在方法的參數中,前提是參數名字必須得跟請求發送的數據的屬性的名字一致,而且這種方式讓請求的參數可為空,請求中沒有參數就為null;
URL形式:
http://localhost:8080/test/two 表單提交數據,其中屬性名與接收的bean內的屬性名一致;
http://localhost:8080/test/two?username=aa&password=bb 數據顯示傳送
構建一個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類中屬性名一致的數據注入User中,沒有的就不注入;
URL形式:
? http://localhost:8080/test/three 采用表單提交數據
? http://localhost:8080/test/three?username=aa 數據顯示傳送
后端請求處理代碼:
@RequestMapping("/three")
public String testThree(HttpServletRequest request){
String username = request.getParameter("username");
System.out.println(username);
return "success";
}
說明:后端采用servlet的方式來獲取數據,但是都用上框架了,應該很少用這種方式來獲取數據了吧;
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注解會將請求路徑中對應的數據注入到參數中
注意:@PathVariable注解的數據默認不能為空,就是請求路徑中必須帶有參數,不能為空,如果請求數據為空,則需要在@PathVariable中將required屬性改為false;
URL形式
http://localhost:8080/test/five 表單提交數據,未顯示傳送
http://localhost:8080/test/two?username=aa&password=bb 數據顯示傳送
后端處理代碼
@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會將請求中相對應的數據注入到參數中。
注意: @RequestParam注解的參數也是不能為空的,如果需要為空,則需要將required屬性改為false,還有就是 @RequestParam注解中的defaultValue 屬性可以為參數設置默認值。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習