SpringBoot学习一:参数传递

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/choath/article/details/87868101

1.get方式Url传参

@PathVariable

    @GetMapping("/hello/{name}")
    public String hello(@PathVariable("name") String name){
        //入参的name取名必须是一致的,但是形参name可以随便取名!
        System.out.println("获取到的值是:"+name);
        return "hello " + name;
    }
访问地址:http://localhost:8080/hello/xiwen

2.get方式Url传参

@RequestParam

备注:如果请求中参数的名字和方法中形参的名字一致,可以省略@RequestParam("name") 

    @GetMapping("/hello")
    public String hello(@RequestParam("name") String name){
        //入参的name取名必须是一致的,但是形参name可以随便取名!
        System.out.println("获取到的值是:"+name);
        return "hello " + name;
    }

访问地址:http://localhost:8080/hello?name=xiwen

3.get方式Url传参

@RequestParam 添加默认值 defaultValue  = “XXX”

    @GetMapping("/hello")
    public String hello(@RequestParam(value = "name",defaultValue = "xiwen") String name){
        //入参的name取名必须是一致的,但是形参name可以随便取名!
        System.out.println("获取到的值是:"+name);
        return "hello " + name;
    }

访问地址:http://localhost:8080/hello?name=xiwen

注意:如果没有给定默认值,并且没有给定参数将会报错,报错信息如下:

Required String parameter 'name' is not present:name参数没有提供

解决方案:

1.defaultValue  = “XXX” :使用默认值

2.required = false :标注参数是非必须的!

4.post方式传递参数

注意事项:看代码注释

      @PostMapping("/user")
      public String hello(@RequestParam("name") String name, String age){
          //入参的name取名必须是一致的,但是形参name可以随便取名!
          //如果入参和形参一直,@RequestParam("name")可以省略
          log.info("name=" + name + "age=" + age);

          return "name=" + name + "age=" + age;
      }

注:post不能直接用浏览器访问,这里测试可以用postman

5.post方式传递字符串文本

通过HttpServletRequest 获取输入流!

    @PostMapping("/postString")
    public java.lang.String postString(HttpServletRequest request){
        ServletInputStream is = null;
        StringBuilder sb = null;
        try {
            is = request.getInputStream();
            sb = new StringBuilder();
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = is.read(buf)) != -1){
                sb.append(new String(buf, 0, len));
            }
            System.out.println(sb.toString());
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(is != null){
                    is.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

6.requestbody接收参数

1.@requestbody可以接收get或者post请求

2.把json作为参数传递,要用RequestBody

3.附带说一下使用postman方式设置content-type为applicantion/json方式测试后台接口

    @PostMapping("/save")
    @ResponseBody
    public Map<String,Object> save(@RequestBody User user){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("user",user);
        return map;
    }

猜你喜欢

转载自blog.csdn.net/choath/article/details/87868101