SpringMVC 框架中,@RequestParam 的简单用法

来源:互联网 发布:怎么用淘宝客买东西 编辑:程序博客网 时间:2024/06/12 20:50



一、获取指定的参数(必填)

controller 中的写法

    @RequestMapping("/fetchItemDetail.do")    @ResponseBody    public String fetchItemDetail(@RequestParam String userName) {        JSONObject json = new JSONObject();        System.out.println("userName = [" + userName + "]");        return json.toJSONString();    }

在上述 controller 方法中用 @RequestParm String userName 指明当前方法接收的参数名称,则在当前 url 请求中必须携带该参数,若前台请求中,未传入当前指定的参数,后台返回 400 错误,如下图


若前台传入多个参数,而后台controller 只设置了一个参数,当请求到达后台 controller 后,后台只会接收当前设定的参数。


二,获取指定的参数(非必填)

controller 中的写法

    @RequestMapping("/fetchItemDetail.do")    @ResponseBody    public String fetchItemDetail(@RequestParam(required = false) String userName) {        JSONObject json = new JSONObject();        System.out.println("userName = [" + userName + "]");        return json.toJSONString();    }

若当前参数非必填,则将 @RequestParm 中设置 require = false  即可。


三、获取指定参数(设默认值)

controller 中的写法

    @RequestMapping("/fetchItemDetail.do")    @ResponseBody    public String fetchItemDetail(@RequestParam(defaultValue = "哈哈哈") String userName) {        JSONObject json = new JSONObject();        System.out.println("userName = [" + userName + "]");        return json.toJSONString();    }
不管当前参数是否为必填,如需要给当前设默认值,则在 @RequestParm 中设置 defaultValue = "需要的默认值" 即可,这样,当前台没有传入该参数时,后台会默认给一个设置的默认值。


四、给指定参数取别名

因为某些原因,当前台 url 请求传送上来的参数和我们后台设置的接收参数名称不一样时,可以用 @RequestParm(name = "前台传入的名称")  进行参数名称转换,SpringMVC 自动将值注入到 后面controller 中设置的接收参数中,如下面代码

    @RequestMapping("/fetchItemDetail.do")    @ResponseBody    public String fetchItemDetail(@RequestParam(name = "name") String userName) {        JSONObject json = new JSONObject();        System.out.println("userName = [" + userName + "]");        return json.toJSONString();    }


上述方法中参数的设置,前台 url 参数传入的参数名称:name  ,后台SpringMVC 会自动将 name中的值注入到后台设置的真实接收参数 userName 中。


以上几种可以在实际运用中进行组合使用。



原创粉丝点击