zoukankan      html  css  js  c++  java
  • SpringBoot web获取请求数据【转】

    SpringBoot web获取请求数据

    一个网站最基本的功能就是匹配请求,获取请求数据,处理请求(业务处理),请求响应,我们今天来看SpringBoot中怎么获取请求数据。

    文章包含的内容如下:

    • 获取请求数据
    • 文件上传
    • 参数校验

    1 获取请求数据

    1.1 获取请求参数数据 @RequestParam

    1.1.1 @RequestParam注解源码了解一下
        // 参数名称
        @AliasFor("name")
        String value() default "";
        // 同上
        @AliasFor("value")
        String name() default "";
        // 是否比传--默认比传
        boolean required() default true;
        // 默认值
        String defaultValue() default ValueConstants.DEFAULT_NONE;
    
    1.1.2 获取请求参数
        /*
        * 设置是否比传,设置默认值
        * http://localhost:8080/requestdata/withParam?name=shuaige哈
        */
        @GetMapping("withParam")
        public String withParam(@RequestParam(name="name",required=true)String name,
                @RequestParam(name="name",required=false,defaultValue="18")String age){
            return "获取的参数数据name:"+name+"age:"+age;
        }
        
        /*
        * 获取多条数据
        * http://localhost:8080/requestdata/withParam2?name=liuawei,刘阿伟
        */
        @GetMapping("withParam2")
        public String withParam(@RequestParam List<String> name){
            return "获取的参数数据name:"+name.toArray().toString();
        }
    

    1.2 获取路径参数数据 @PathVariable

        @GetMapping("withPath/{userId}/info")
        public String withPath(@PathVariable String userId){
            return "获取请求路径参数"+userId;
        }
    

    1.3 获取header数据 @RequestHeader

        @GetMapping("withHeader")
        public String withHeader(@RequestHeader String token){
            return "获取请求头参数"+token;
        }
    

    1.4 获取cookie数据 @CookieValue

        @GetMapping("withCookie")
        public String withCookie(@CookieValue String token){
            return "获取cookie参数"+token;
        }
    

    1.5 获取请求内容(body)数据 @RequestBody

    GET请求没有body内容,所以不需要这个注解

        /**
         * 获取字符串内容
         * @param list
         * @return
         */
        @PostMapping("withBody1")
        public String withBody1(@RequestBody String body){
            return "获取请求内容数据1:"+body;
        }
        /**
         * 获取MAP对象
         * @param list
         * @return
         */
        @PostMapping("withBody3")
        public String withBody3(@RequestBody Map<String, String> body){
            return "获取请求内容数据3:"+body;
        }
        /**
         * 获取实体
         * @param list
         * @return
         */
        @PostMapping("withBody4")
        public String withBody4(@RequestBody UserInfoModel body){
            return "获取请求内容数据4:"+body;
        }
        /**
         * 获取列表
         * @param list
         * @return
         */
        @PostMapping("withBody6")
        public String withBody6(@RequestBody List<Map<String, Object>> list){
            return "获取请求内容数据6:"+list.toArray().toString();
        }
    

    1.6 获取FORM表单参数

    /**
         * 获取FORM表单数据  通过参数
         * @param formKey1
         * @param formKey2
         * @return
         */
        @PostMapping("withForm1")
        public String withForm1(@RequestParam String formKey1,@RequestParam String formKey2){
            return "获取FORM表单参数formKey1:"+formKey1+" :formKey2:"+formKey2;
        }
        
        /**
         * 获取FORM表单数据 通过对象
         * @param userInfo
         * @return
         */
        @PostMapping("withForm2")
        public String withForm2(@ModelAttribute UserInfoModel userInfo){
            return "获取FORM表单参数:"+userInfo.toString();
        }
    

    1.7 我是BOSS,上面都是我小弟

    上面的注解都是Spring把请求流的数据帮我们封装成对象,方便我们使用,所有的数据都可以从HttpServletRequest对象可以获取。

        @PostMapping("withRequest")
        public String withRequest(HttpServletRequest request) throws IOException{
            // 获取请求参数
            request.getParameter("");
            // 获取请求头
            request.getHeader("");
            // 获取cookie
            request.getCookies();
            // 获取路径信息 
            request.getPathInfo();
            // 获取body流
            request.getInputStream();
            return "其实上面讲了那么多,这个才是大BOOS";
        }
    

    2 文件上传

    **MultipartFile **

        /**
         * @param file
         * @return
         * @throws IOException
         */
        @PostMapping("/image")
        public String uploadImage(@RequestParam MultipartFile file) throws IOException{
            String contentType = file.getContentType();
            if (contentType.equals(MediaType.IMAGE_JPEG_VALUE)
                    ||contentType.equals(MediaType.IMAGE_PNG_VALUE)) {
                // 获取文件流
                InputStream is= file.getInputStream();
                byte[] data = new byte[2048];
                FileOutputStream fis = new FileOutputStream(
                        new File("D:\liuawei\springbootbucket\resources\upload\"+file.getOriginalFilename()));
                while(is.read(data)!=-1){
                    fis.write(data);
                }
                fis.flush();
                fis.close();
                is.close();
            }else {
                return "error";
            }
            return "success";
        }   
    

    3 参数校验

    添加参数校验框架依赖

    <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>6.0.13.Final</version>
    </dependency>
    
    1. 在JavaBean上面配置检验规则
        @Min(value=15,message="最小值是15")
        @Max(value=130,message="最大值是130")
        private int age;
        
        @Email(message="必须符合邮件地址")
        private String email;
        
        @Past(message="日期是过去的日期")
        @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
        private Date birthday;
        
        @NotBlank
        private String remark;
    
    1. 在请求方法添加@Valid进行校验
        @GetMapping("validata")
        public String validata(@Valid ValBean bean,BindingResult result){
            if (result.hasErrors()) {
                return "参数校验失败";
            }
            return "参数校验成功";
        }
    

    4 参考

    https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-file-upload
    https://blog.lqdev.cn/2018/07/20/springboot/chapter-eight/
    

    源码下载 :GitHub
    请求示例 :用例地址

    传送门SpringBoot学习总结系列文章



    作者:liuawei
    链接:https://www.jianshu.com/p/1a59c923087d
    来源:简书
    简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
  • 相关阅读:
    STL中的栈 P1739 表达式括号匹配
    STL中的队列
    破损的键盘(又名:悲剧文本)(Broken Keyboard(a.k.a. Beiju Text), UVa 11988)
    粤语学习笔记(二)万门大学第6课完
    粤语学习笔记(一)
    VerilogHDL学习笔记(一)--来自一个小彩袅
    Eigen学习笔记(一)-----安装
    松耦合和紧耦合
    ProxyPattern
    git的使用以及github
  • 原文地址:https://www.cnblogs.com/whatlonelytear/p/11270525.html
Copyright © 2011-2022 走看看