SpringBoot如何优雅接收请求参数

您所在的位置:网站首页 svf2n65f的参数 SpringBoot如何优雅接收请求参数

SpringBoot如何优雅接收请求参数

2023-10-31 21:10| 来源: 网络整理| 查看: 265

@RequestParm

我们可以通过@RequestParm注解去绑定请求中的参数,将(查询参数或者form表单数据)绑定到controller的方法参数中,通俗点说就是,我们可以在get请求和post请求中使用改注解,get请求中会从查询参数中获取参数,post请求会从form表单或者查询参数中获取参数

默认情况下,方法参数上使用该注解说明这个参数是必传的,但是我们可以通过required = false来设置是否必传,或者通过defaultValue设置默认值。 如果类型不是Sting类型的话,会自动进行转换 可以将参数类型声明为list,同一个参数名解析多个参数值 1.使用Get请求    /**     *GET http://localhost:8080/api/person/getPerson?id=1     */    @GetMapping("/getPerson")    public String getPerson(@RequestParam(value = "id",required = false,defaultValue = "2") Integer id) {        log.info("id:{}", id);        return "";   } 2.使用Post请求    /**     * POST http://localhost:8080/api/person/postPerson     * Content-Type: application/x-www-form-urlencoded     *     * id=1     */    @PostMapping("/postPerson")    public String postPerson(@RequestParam("id") String id) {        log.info("id:{}", id);        return "";   } 3.使用Map接收    /**     *POST http://localhost:8080/api/person/postPersonMap     * Content-Type: application/x-www-form-urlencoded     *     * id=1     */    @PostMapping("/postPersonMap")    public String postPersonMap(@RequestParam HashMap param) {        log.info("param:{}",param.toString());        return "";   } 4.使用List接收    /**     *可以通过两种方式传递list     * 第一种传递到param中:     * POST http://localhost:8080/api/person/postPersonList?param=1,2,3,4     *     * 第二种传递到form表单中:     * POST http://localhost:8080/api/person/postPersonList     * Content-Type: application/x-www-form-urlencoded     *     * param=1,2,3,4,5     */    @PostMapping("/postPersonList")    public String postPersonList(@RequestParam List param) {        log.info("param:{}",param);        return "";   } 5.什么都不加

如果不加的话,前端可以不传id。默认:get请求通过param传递,post请求通过form表单传递

   /**     * GET http://localhost:8080/api/person/getPerson?id=1     */    @GetMapping("/getPersonById")    public String getPersonById(Integer id) {        log.info("id:{}", id);        return "";   } @RequestBody

@RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的);

如果参数未传的话,引用类型默认是null,基本类型为默认值

注:一个请求,只有一个RequestBody;一个请求,可以有多个RequestParam。

### test postPersonByJson POST http://localhost:8080/api/person/postPersonByJson Content-Type: application/json ​ {  "id": 1,  "name": "tom",  "age": 12,  "ADDRESS": "beijing" }

默认json的key和属性名称必须要匹配的,并且大小写敏感

如果有别名的话可以使用@JsonAlias注解或者使用@JsonProperty注解如下:

   /**     * 地址     */ ​    @JsonAlias(value = {"ADDRESS"})    private String adress;    /**     * 地址     */ ​   @JsonProperty("ADDRESS")    private String adress;

服务端接收如下:

​    @PostMapping("/postPersonByJson")    public Person postPersonByJson(@RequestBody Person person) {        log.info("person:{}", person);        return person;   } HttpEntity

HttpEntity 和@RequestBody使用相同,多了一个header

### test httpEntity POST http://localhost:8080/api/person/accounts Content-Type: application/json ​ {  "id": 1,  "name": "tom",  "age": 12,  "ADDRESS": "beijing" }    /**     * HttpEntity 和@RequestBody使用相同,多了一个header     *     * @param entity     */    @PostMapping("/accounts")    public void handle(HttpEntity entity) {        log.info("请求头部为:{},请求体为:{}", entity.getHeaders(), entity.getBody());   } @RequestHeader

@RequestHeader 主要用于接收前端header中的参数,可以获取指定的header属性,也可以通过Map统一接收请求头中的参数

### test header GET http://localhost:8080/api/person/getPersonHeader Accept-Encoding: deflate Keep-Alive: 11 ​ ### test headerByMap GET http://localhost:8080/api/person/getPersonHeaderByMap Accept-Encoding: deflate Keep-Alive: 11 ​    /**     * 接收header参数     */    @GetMapping("/getPersonHeader")    public void getPersonHeader(@RequestHeader("Accept-Encoding") String encoding,                                @RequestHeader("Keep-Alive") long keepAlive) {        log.info("Accept-Encoding:{},Keep-Alive:{}", encoding, keepAlive);   } ​    /**     * map接收header参数     * 使用map接收key值会变成小写     */    @GetMapping("/getPersonHeaderByMap")    public void getPersonHeader(@RequestHeader Map param) {        param.forEach((key, value) -> {            log.info("key:{},value:{}", key, value);       });        log.info("Accept-Encoding:{},Keep-Alive:{}", param.get("accept-encoding"), param.get("keep-alive"));   } ​ @PathVariable

使用@PathVariable注解可以获取url中的参数,也可以使用正则表达式提取url中的多个变量

### test PathVariable GET http://localhost:8080/api/person/1 ​ ​ ### test PathVariable regular expression GET http://localhost:8080/api/person/express/spring-web-3.0.5.jar    /**     * 获取url中的参数     */    @GetMapping("/{id}")    public void getPersonById(@PathVariable String id) {        log.info("id:{}", id);   } ​    /**     * 通过正则表达式获取url中name,version,ext等信息     */    @GetMapping("/express/{name:[a-z-]+}-{version:\d\.\d\.\d}{ext:\.[a-z]+}")    public void handle(@PathVariable String name, @PathVariable String version, @PathVariable String ext) {        log.info("name:{},version:{},ext:{}", name, version, ext);   } @ModelAttribute

@ModelAttribute可以作用在方法上和方法参数上,

标记在方法的参数上,会将客户端传递过来的参数按名称注入到指定对象中 标记在方法上,会在每一个@RequestMapping标注的方法前执行。 ###test modelAttribute POST http://localhost:8080/api/person/postPersonByModel/123 Content-Type: application/x-www-form-urlencoded ​ name=tom&age=14&address=北京 ​ ​ ​ ###test getModelAttribute GET http://localhost:8080/api/person/getPersonByModel/456?name=tom&age=14&address=北京 ​    @PostMapping("/postPersonByModel/{id}")    public void postPersonByModel(@ModelAttribute Person person) {        log.info("person:{}", person);   } ​    @GetMapping("/getPersonByModel/{id}")    public void getPersonByModel(@ModelAttribute Person person) {        log.info("person:{}", person);   }

或者将@ModelAttribute注解放到方法上,如果有公共参数需要进行处理,可以使用@ModelAttribute进行前置操作例如:

### testModelAttribute POST http://localhost:8080/api/person/testModelAttribute Content-Type: application/x-www-form-urlencoded token: 123 ​ name=tom&age=14&address=北京    @ModelAttribute    public void userInfo(ModelMap modelMap, HttpServletRequest request) {        log.info("执行modelAttribute方法");        //模拟通过token获取userId的过程        String id = request.getHeader("token").toString();        modelMap.addAttribute("userId", id);   } ​    @PostMapping("/testModelAttribute")    public void testModelAttribute(@ModelAttribute("userId") String userId, Person person) {        log.info("userId:{}", userId);   }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3