美文网首页
SpringMvc请求参数传递方式

SpringMvc请求参数传递方式

作者: 熊妈妈宝典 | 来源:发表于2018-06-02 18:22 被阅读32次

    1.使用请求参数

    关键字@RequestParam
    请求示例http://localhost:8080/index/getString?name=lovetoday&id=10000
    使用场景当URL需要对资源或者资源列表进行过滤,筛选时使用这种方式。

    //方式1
        @RequestMapping(value = "/getString", method = RequestMethod.GET)
        public String getString(int id, String name) {
            return name+"'s id is: "+id;
        }
    

    请求结果:


    注意:
    使用http://localhost:8080/index/getString进行访问时,会报异常。

    原因在于Controller方法参数中定义的是基本数据类型,但是从页面提交过来的数据为null或者""的话,会出现数据转换的异常。也就是必须保证表单传递过来的数据不能为null或”",所以,在开发过程中,对可能为空的数据,最好将参数数据类型定义成包装类型。

    //修改方法1:
        @RequestMapping(value = "/getString", method = RequestMethod.GET)
        public String getString(Integer id, String name) {
            return id + name;
        }
    

    一旦我们在方法中定义了@RequestParam变量,如果访问的URL中不带有相应的参数,就会抛出异常,Spring尝试帮我们进行绑定,然而没有成功。但有的时候,参数确实不一定都存在,这时可以通过定义required属性,@RequestParam(name="id",required=false)。当然,在参数不存在的情况下,可能希望变量有一个默认值:@RequestParam(name="id",required=false,defaultValue="0")

     //修改方法2
        @RequestMapping(value = "/getValue", method = RequestMethod.GET)
        public User getUser(@RequestParam(name = "id", required = false, defaultValue = "0") int id,
                            @RequestParam(name = "name", required = false, defaultValue = "lovetoday") String name) {
            User user = new User();
            user.setId(id);
            user.setName(name);
            return user;
        }
    

    2.使用路径参数

    关键字@PathVariable
    请求示例1http://localhost:8080/index/find/1000/lovetoday
    使用场景当URL指向的是某一具体业务资源(或者资源列表),例如博客中的用户、文章列表、文章时。

     @RequestMapping(value = "/find/{id}/{name}")
        public String find(@PathVariable String name, @PathVariable int id) {
            return name +"'s id: "+id;
        }
    

    请求示例2http://localhost:8080/index/find/ ----报404


    3.通过HttpServletRequest

    post方式和get方式都可以

    待更新

    4.通过RequestBody

    post方式
    待更新

    相关文章

      网友评论

          本文标题:SpringMvc请求参数传递方式

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