12

java 后台 controller 接收参数的几种 方式

 3 years ago
source link: http://www.hechunbo.com/index.php/archives/402.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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 protected]

2.请求参数名和Controller方法中的对象的参数一致

 @GetMapping("/employee")
    public String addEmployee(Employee employee){
        return null;
    }
//调用http://127.0.0.1:8080/test/employee?lastName=战三&[email protected]

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 protected]

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 ""
})
    

https://www.jianshu.com/p/05092349b0f2


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK