spring boot controller 参数接收方式
一.非json接收
1.url请求参数名==方法名
public String addEmployee(String lastName,String email){
return null;
}
//调用 http://127.0.0.1:8080/add?lastName=aa&email=test@12.com
2.请求参数名和Controller方法中的对象的参数一致
@GetMapping("/employee")
public String addEmployee(Employee employee){
return null;
}
//调用http://127.0.0.1:8080/test/employee?lastName=战三&email=dd@qq.com
3.自定义方法参数
当url中的参数和controller中 参数 不一样时,用注解 @RequestParam
@GetMapping("/deport")
public String addEmployee(@RequestParam("name") String lastName,@RequestParam String email){
return "lastName:"+lastName+",email:"+email;
}
//调用http://127.0.0.1:8080/deport?name=张三&email=ss@qq.com
4.获取路径中接收的参数
@GetMapping("/emp/{id}")
public Employee getEmpById(@PathVariable("id") Integer id){
log.info("查询顾客");
return employeeMapper.getEmpById(id);
}
//http://127.0.0.1:8080/emp/1
二,json格式接收
1.json格式接收对象
@PostMapping("/test")
public String addEmployee(@RequestBody Employee employee){
return "lastName:"+employee.getLastName()+",email:"+employee.getEmail();
}
//http://127.0.0.1:8080/resp/test
2.json接收List对象
@PostMapping("/testlist")
public String addEmployee(@RequestBody List<Employee> employees){
StringBuilder sb = new StringBuilder("{");
if( null != employees){
for(Employee employee:employees){
sb.append("{"+"lastName:"+employee.getLastName()+",email:"+employee.getEmail()+"}");
}
}
sb.append("}");
return sb.toString();
}
//调用 http://127.0.0.1:8080/resplist/testlist
json格式接收MAP对象
@PostMapping("/testmap")
public String addEmployee(@RequestBody Map<String,Employee> employees){
StringBuilder sb = new StringBuilder("[");
if( null != employees){
for(Map.Entry<String,Employee> employeeEntry : employees.entrySet()){
sb.append(employeeEntry.getKey()+":"+employeeEntry.getValue()+",");
}
}
sb.append("]");
return sb.toString();
}
//调用 http://127.0.0.1:8080/respmap/testmap
4.post单独接收一个id
@PostMapping(value="getUserById")
Public String getUserById(@RequestBody Integer id){
return ""
}
//调用 $.post.json("jtest/getUserByid",JSON.stringfy(id),function(d){
return ""
})
接收单个参数请飞机到
http://www.hechunbo.com/index.php/archives/407.html
参考:
还不快抢沙发