美文网首页
SpringMVC如何接收前端传递的参数

SpringMVC如何接收前端传递的参数

作者: Insecurity | 来源:发表于2020-05-17 00:07 被阅读0次

    一、@RequestParam注解

    1.@RequestParam 获取注解
       1.get/post  url =>"xx/user?id=1"    action =>public String User( @RequestParams(name="id") Long id ){}。
       2.@RequestParam定义的参数 会自动解析为 方法定义的类型。
    @RequestParams(name="id") Long id )(通过postman模拟post请求)
    

    二、@PathVariable注解

    1.@PathVariable获取注解
      1.get/post  url =>"xx/user/1"    action =>public String User( @PathVariable(name="id") Long id){}
      2.@PathVariable必须通过正则指定对应的类型 只有当url指定为数字,方法参数定义为数字类型才不会报错。比如:(可以通过其他正则限制url,只有符合条件的url才会映射到对应的action,否则不会找到对应的action)
      @RequestMapping("/user/{id:\\d}")
      public String User( @PathVariable(name="id") Long id){}
    

    三、SpringMVC的自动解析参数

      1.SpringMVC,可以不设置任何注解即可接收参数,比如 
       @GetMapping("/category")
       public String category( Long id) {
        System.out.println(id);
        return "post/category";
    }
      可以通过  /category 访问 ,也可以通过 /category?id=1 访问
    2.SpringMVC ,也可以自动包装成对象 
       url  /category?title=测试    或者  /category  都能访问到目标资源
    
        @GetMapping("/category")
        public String category( MPost post ) {
            System.out.println(post.getTitle());
            return "post/category";
        }
    
    

    四、SpringMVC的@RequestBody注解

    1.@RequestBody 用来接收数组或者复杂对象(必须将参数放在requestbody中,放在url并不会被解析,哪怕请求方式是post)
    2. url  => /category  requestbody =>{"id":1}
        @PostMapping("/category")
        public String category( @RequestBody Post post ) {
            System.out.println(post.getTitle());
            return "post/category";
        }
    3.若为对象数组,将方法参数改为 @RequestBody List<Post> post  即可
    4.直接输入 /category并不会找到对应的action
    

    五、总结

      1.SpringMVC的自动封装(不传参也能进入)
      @RequestParam(必须传参,但可以手动设置为false) 
      @PathVariable(符合设定的正则表达式才允许进入,而且不能为空)
      2.对比可知,主要是为了url提供更加严格的限制,以防止一些其他url进入该action。
      3.提供复杂的接受参数的方式@RequestBody ,但必须将参数放置在@RequestBody中
      4.针对PathVariable 需要注意的是参数中包含特殊字符的问题,可能导致参数不全。
      5.对于各种请求方式,验证一下当前用户,对url进行加密 是有必要的。(尤其是关键数据)
    

    相关文章

      网友评论

          本文标题:SpringMVC如何接收前端传递的参数

          本文链接:https://www.haomeiwen.com/subject/bredohtx.html