僅使用get方法來進行演示,其他請求方法(POST,DELETE,PUT)接受參數的形式都是一樣的。
-
用數組接受參數
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class CIsBestController { // 訪問路徑 http://localhost:8080/array?strings="貂蟬學python","小喬學java","魯班學C++" // 瀏覽器顯示的結果:響應數據:"貂蟬學python","小喬學java","魯班學C ", @RequestMapping("/array") @ResponseBody public String resp(String[] strings) { String str = ""; for(String s:strings){ System.out.println("接受的參數是:" + s); str += s+","; } return "響應數據:" + str; } }
-
用List接受參數
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.util.ArrayList; @Controller public class CIsBestController { // 訪問路徑 http://localhost:8080/list?array_list="貂蟬學python","小喬學java","魯班學C++" // 瀏覽器顯示的結果:響應數據:"貂蟬學python","小喬學java","魯班學C ", @RequestMapping("/list") @ResponseBody public String resp(@RequestParam("array_list") ArrayList<String> arrayList) { String str = ""; for(String s:arrayList){ System.out.println("接受的參數是:" + s); str += s+","; } return "響應數據:" + str; } }
-
用Map接受參數
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.util.Map; @Controller public class CIsBestController { // 訪問路徑 http://localhost:8080/map?name=貂蟬&age=18&sex=女 // 瀏覽器顯示的結果:響應數據:{name=貂蟬, age=18, sex=女} @RequestMapping("/map") @ResponseBody public String resp(@RequestParam Map map) { System.out.println(map); return "響應數據:" + map; } }
關於用Map接受參數有個小坑,用Map接受參數必須要在參數前添加
@RequestParam
注解。Map不能用來接受復合參數。對於前端來說,Map只能接受
{ name : "貂蟬", age : 18, sex : "女" }
這種形式的參數。如果前端傳的是
{ name : "貂蟬", age : 18, sex : "女", spouse : { name : "呂布", age: 25, sex: "男" } }
Map 是拿不到
spouse
里面的參數信息的。import lombok.Data; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.util.Map; @Data class Spouse{ private String name; private String age; private String sex; } @Controller public class CIsBestController { // 訪問路徑 http://localhost:8080/map?name=貂蟬&age=18&sex=女&spouse.name=呂布&spouse.age=25&spouse.sex=男 @RequestMapping("/map") @ResponseBody public String resp(@RequestParam Map map) { System.out.println(map); String name = (String) map.get("name"); System.out.println(name); Spouse spouse = (Spouse) map.get("spouse"); System.out.println(spouse.getName()); return "響應數據:" + spouse.toString(); } }
訪問地址
http://localhost:8080/map?name=貂蟬&age=18&sex=女&spouse.name=呂布&spouse.age=25&spouse.sex=男
,會報java.lang.NullPointerException
的異常。