Springboot 最细节全面的接口传参接参介绍,总有你喜欢的一种方式

简介: Springboot 最细节全面的接口传参接参介绍,总有你喜欢的一种方式

这篇里面对每种传参接参方式都会举出较多的例子,不多说,入正题:


@PathVariable




    @GetMapping("/getId/{id}")
    public String pathVariableTest(@PathVariable Integer id) {
        return  "id:   "+id;
    }

    @GetMapping("/getId/{id}")
    public String pathVariableTest(@PathVariable("id") Integer id) {
        return  "id:   "+id;
    }

    @GetMapping("/getId/{idValue}")
    public String pathVariableTest(@PathVariable("idValue") Integer id) {
        return  "id:   "+id;
    }



以上三种方式的调用结果都是成功的:


image.png


虽然说三种方式都是成功的,但是推荐使用第二种,也就是明确地指定对应参数对应名称。


第一种方式不注明参数名称的,仅仅在单个参的时候选择使用。


最后给出推荐使用的第二种方式的传接多参例子:


    @GetMapping("/getIdAny/{id}/{name}")
    public String pathVariableTestAny(@PathVariable("id") Integer id,@PathVariable("name") String name) {
        return  "**id:   "+id+"  **name:        "+name;
    }



调用结果(http://localhost:8023/getId/1001/JCccc):


image.png


@RequestParam



    @GetMapping("/getId")
    public String requestParamTest( Integer id) {
        return  "id:   "+id;
    }


 

    @GetMapping("/getId")
    public String requestParamTest( @RequestParam Integer id) {
        return  "id:   "+id;
    }



    @GetMapping("/getId")
    public String requestParamTest( @RequestParam("id") Integer id) {
        return  "id:   "+id;
    }


以上三种方式都是可以正常调用的:


image.png



    @GetMapping("/getId")
    public String requestParamTest( @RequestParam("idValue") Integer id) {
        return  "id:   "+id;
    }


第四种,可以看到在@RequestParam里面给参数id取名为: idValue,这时候传参时参数名称也需要写成idValue即可。


image.png


那么以上四种方式,我推荐第三种,也就是规范地注解命名对应参数名称。


最后给出推荐使用的第三种方式的传接多参例子:


    @GetMapping("/getIdAny")
    public String requestParamTestAny( @RequestParam("id") Integer id,@RequestParam("name") String name,@RequestParam Integer age) {
        return  "**id:   "+id+"    **name:   "+name+"    **age:   "+age;
    }


调用结果(http://localhost:8023/getIdAny?id=1002&name=JCccc&age=10):


image.png


上传文件


针对使用@RequestParam,补充一下上传文件的是需要注意的以及方式:


简单示例一下怎么接收以及传递文件(使用MultipartFile接收):


    @ResponseBody
    @PostMapping("upload")
    public String upload(@RequestParam("myFile") MultipartFile file)  {
        return "---file name:" + file.getOriginalFilename()+
                "---file type:" + file.getContentType()+
                "---file size:" + file.getSize();
    }


image.png


@RequestBody


PS:对应RequestBody的使用,方式其实是比较多的,可以耐心看看,传参以json格式传递,接收方式较多(一定要记住Content-Type为application/json


通过实体类接参的方式:


User.java:

image.png

PS:Get 方式 和 Post方式 其实都是可以有requestBody的,只不过一般来说post用的较多(后面都用post方式举例)。


    @GetMapping("/getRequestBodyValue")
    public String RequestBodyTest(@RequestBody User user) {
        return  user.toString();
    }


调用结果:

image.png


通过Map接参的方式:


单独获取参通过map的get方法根据key获取即可


    @PostMapping("/getRequestBodyValue")
    public String RequestBodyTest(@RequestBody Map userMap) {
        return  userMap.toString();
    }


调用结果:

image.png


通过JsonObject接参的方式:


这里用到了fastjson的依赖包:


        <!--添加fastjson依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.7</version>
        </dependency>
    @PostMapping("/getRequestBodyValue")
    public String RequestBodyTest(@RequestBody JSONObject jsonObject) {
        Integer id = jsonObject.getInteger("id");
        String name = jsonObject.getString("name");
        Integer age = jsonObject.getInteger("age");
        return  "---id:"+id+"  ---name:"+name+"  ---age:"+age;
    }


调用结果:


image.png


通过String接参数的方式:


这种情况是先使用String把body里面的数据获取出来,再转换成jsonobject再进行参数解析


    @PostMapping("/getRequestBodyValue")
    public String RequestBodyTest(@RequestBody String jsonStr) {
        JSONObject jsonObject= JSON.parseObject(jsonStr); //将jsonStr转化为JSONObject,再进行取值
        Integer id = jsonObject.getInteger("id");
        String name = jsonObject.getString("name");
        Integer age = jsonObject.getInteger("age");
        return  "---id:"+id+"  ---name:"+name+"  ---age:"+age;
    }


调用结果:


image.png


另外补充这种没有通过json格式传参的,以实体类传参接参方式:


举例使用User实体类,User.java:


image.png

    @GetMapping("/getValue")
    public String entityValueTest( User user) {
        return  user.toString();
    }


调用方式(参数名需与实体类字段名报持一致):


全部参数都传,


image.png


只传部分参数,


image.png


@RequestHeader:



这是取出放在header里面的值,如:


    @ResponseBody
    @RequestMapping("/getMyHeaderParam")
    public String getOrderList(@RequestHeader String token,@RequestHeader String uuid) {
        return "----token:"+token+"--- uuid:"+uuid;
    }

image.png


HttpServletRequest :



    @GetMapping("/getHttpServletRequest")
    public String httpServletRequestValueTest(HttpServletRequest request) {
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        return  "---id:"+id+"  ---name:"+name+"  ---age:"+age;
    }
    @GetMapping("/getHttpServletRequest")
    public String httpServletRequestValueTest(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        String[] ids = parameterMap.get("id");
        String[] names = parameterMap.get("name");
        String[] ages = parameterMap.get("age");
        String id = ids[0];
        String name =names[0];
        String age =ages[0];
        return  "---id:"+id+"  ---name:"+name+"  ---age:"+age;
    }


以上两种方式调用结果:


image.png


通过HttpServletRequest 获取body里面的json数据:


(其实这种方式是较为麻烦的,不太推荐,还不如使用上面提到的@RequestBody好了)


    @PostMapping("/getHttpServletRequest")
    public String get(HttpServletRequest request) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String str = "";
        String wholeStr = "";
        //一行一行的读取body体里面的内容
        while((str = reader.readLine()) != null){
            wholeStr += str;
        }
        //转化成JSONObject
        JSONObject jsonObject=JSONObject.parseObject(wholeStr);
        Integer id =  jsonObject.getInteger("id");
        String name = jsonObject.getString("name");
        Integer age = jsonObject.getInteger("age");
        return  "---id:"+id+"  ---name:"+name+"  ---age:"+age;
    }


调用结果:


image.png


OK,各种方式获取参数介绍就到此。


---------------------------------


对于评论中问到Get请求方式,RequestBody 能不能使用? 其实文中我有说到是可以的,只是不推荐

(其实跟的GET请求跟POST请求的所为的区别都是虚假,只能说是一种约束,规定。因为本身的HTTP协议上,人家可没说body只能Post请求使用;人家也没说GET和POST有长度限制,只不过是因为浏览器和服务器的种种原因生成了一些规定而已。这种东西就不展开了,了解知道就行。)。


示例:


image.pngimage.png


结果(能正常接收到):


image.png


调试接口的工具,可以参考这篇:


做一个合格的开发,从玩转Apipost开始_小目标青年的博客-CSDN博客_apipost压测

相关文章
|
2月前
|
Java API 微服务
【Spring Boot系列】通过OpenAPI规范构建微服务服务接口
【4月更文挑战第5天】通过OpenAPI接口构建Spring Boot服务RestAPI接口
140 0
|
2月前
|
存储 JSON Java
SpringBoot集成AOP实现每个接口请求参数和返回参数并记录每个接口请求时间
SpringBoot集成AOP实现每个接口请求参数和返回参数并记录每个接口请求时间
83 2
|
27天前
|
存储 Java 数据安全/隐私保护
Spring Boot中实现邮箱登录/注册接口
Spring Boot中实现邮箱登录/注册接口
|
11天前
|
Java 数据库连接 Maven
文本,使用SpringBoot工程创建一个Mybatis-plus项目,Mybatis-plus在编写数据层接口,用extends BaseMapper<User>继承实体类
文本,使用SpringBoot工程创建一个Mybatis-plus项目,Mybatis-plus在编写数据层接口,用extends BaseMapper<User>继承实体类
|
11天前
|
Java
软件开发常用之SpringBoot文件下载接口编写(下),Vue+SpringBoot文件上传下载预览,服务器默认上传是1M,可以调节,调节文件上传大小写法,图片预览,如何预览后下次还能看到,预览写法
软件开发常用之SpringBoot文件下载接口编写(下),Vue+SpringBoot文件上传下载预览,服务器默认上传是1M,可以调节,调节文件上传大小写法,图片预览,如何预览后下次还能看到,预览写法
|
11天前
|
文字识别 Java Python
文本,文识10,springBoot提供RestTemplate以调用Flask OCR接口,调用flask实现ocr接口,用paddleocr进行图片识别云服务技术,单个paddleocr接口有影响
文本,文识10,springBoot提供RestTemplate以调用Flask OCR接口,调用flask实现ocr接口,用paddleocr进行图片识别云服务技术,单个paddleocr接口有影响
|
11天前
|
文字识别 Java
文本,文字识别07,SpringBoot服务开发-入参和返回值,编写接口的时候,要注意识别的文字返回的是多行,因此必须是List集合,Bean层,及实体类的搭建
文本,文字识别07,SpringBoot服务开发-入参和返回值,编写接口的时候,要注意识别的文字返回的是多行,因此必须是List集合,Bean层,及实体类的搭建
|
11天前
|
文字识别 Java Spring
文本,文字识别,SpringBoot服务开发,SpringBoot如何提供上传服务,接口的设计,它做了将Base64重新转为图片,SpringBoot的应用实例,项目基础搭建
文本,文字识别,SpringBoot服务开发,SpringBoot如何提供上传服务,接口的设计,它做了将Base64重新转为图片,SpringBoot的应用实例,项目基础搭建
|
17天前
|
Dubbo Java 应用服务中间件
Spring Boot 调用 Dubbo 接口与编写 Dubbo 接口实战
Spring Boot 调用 Dubbo 接口与编写 Dubbo 接口实战
43 1
|
25天前
|
算法 Java API
在Spring Boot中实现接口签名验证通常涉及以下步骤
在Spring Boot中实现接口签名验证通常涉及以下步骤
43 4