@Controller
@RequestMapping("/home")
public class XDController {
@GetMapping("/dxd")
@ResponseBody
public String getName(){
System.out.println("其实进来了!");
return "xiaodong";
}
@GetMapping("/dxd/{uid}")
@ResponseBody
public String path(@PathVariable("uid") String uid){
return "/path/+"+uid;
}
@GetMapping("/{dxd}/shuai")
@ResponseBody
public String midPath(@PathVariable("dxd") String uid){
return "/path/+"+uid;
}
@PostMapping("/getName")
@ResponseBody
public String pingjieParams(String name){
return "my name is " + name;
}
@PostMapping("/getBody")
@ResponseBody
public String bodyParams(@RequestBody String name){
System.out.println("jinlale");
return "my name is " + name;
}
@PostMapping("/body")
@ResponseBody
public String bodyP(@RequestBody BodyP bodyP){
System.out.println("jinlale");
return "my name is " + bodyP.getName();
}
/**
* localhost:8080/home/delivery?add=xian&name=zhansan&age=12
* 表单提交的形式,拼接在路径上后端用对象接收。
* */
@PostMapping("/delivery")
@ResponseBody
public String receive(BodyP bodyP){
System.out.println("jinlale");
return "my name is " + bodyP.getName() + bodyP.getAdd();
}
/**
* localhost:8080/home/delivery_ages?ages=xian&ages=zhansan&ages=12
*
* my name is xian--zhansan--12
* */
@PostMapping("/delivery_ages")
@ResponseBody
public String receive(String[] ages){
System.out.println("jinlale");
String collect = String.join("--", ages);
return "my name is "+collect;
}
/** @RequestParam
* 如果参数被此注解修饰,必须传其设置的属性(name 或者value设置的属性),否则会报错,
* 如果设置了 defaultzValue 则当必传属性为空时,使用此值。
* 感觉和不用此注解修饰的表单提交方式功能稍微强大点
* */
@PostMapping("/requestPar")
@ResponseBody
public String rev(@RequestParam(name = "xingming", defaultValue = "王老五") String name,String add){
return "my name is "+ name +"--" + add;
}
/**
* RequestParam 修饰map 通过map传参
* localhost:8080/home/requestPar/map?name=testname&pwd=123456
* my name is {name=testname, pwd=123456}
* 经过验证如果不加@RequestParam 是获取不到参数的
* */
@PostMapping("/requestPar/map")
@ResponseBody
public String map(@RequestParam Map<String,String> params){
return "my name is "+ params;
}
private static class BodyP{
private int age;
private String name;
private String add;
// ...
}
}
总的来说主要有三种形式:
form表单提交@RequestParam,使用@PathVariable占位符,对象传参@RequestBody。
特别说明下在表单提交中可以不需要任何注解修饰,@RequestParam只是对默认提交方式的加强从表象上看是这样的,具体原理未深入了解。