当前位置 博文首页 > 文章内容

    @PathVariable注解,让spring支持参数带值功能的案例

    作者:shunshunshun18 栏目:未分类 时间:2021-02-23 14:43:50

    本站于2023年9月4日。收到“大连君*****咨询有限公司”通知
    说我们IIS7站长博客,有一篇博文用了他们的图片。
    要求我们给他们一张图片6000元。要不然法院告我们

    为避免不必要的麻烦,IIS7站长博客,全站内容图片下架、并积极应诉
    博文内容全部不再显示,请需要相关资讯的站长朋友到必应搜索。谢谢!

    另祝:版权碰瓷诈骗团伙,早日弃暗投明。

    相关新闻:借版权之名、行诈骗之实,周某因犯诈骗罪被判处有期徒刑十一年六个月

    叹!百花齐放的时代,渐行渐远!



    @PathVariable的作用

    获取URL动态变量,例如

      @RequestMapping("/users/{userid}")
      @ResponseBody
      public String getUser(@PathVariable String userid){
        return "userid=" + userid; 
      }

    @PathVariable的包引用

    spring自从3.0版本就引入了org.springframework.web.bind.annotation.PathVariable,

    这是RESTful一个具有里程碑的方式,将springMVC的精华推向了高潮,那个时代,跟微信公众号结合的开发如火如荼,很多东西都会用到URL参数带值的功能。

    @PathVariable的PathVariable官方doc解释

    - Annotation which indicates that a method parameter should be bound to a URI template variable. Supported for RequestMapping annotated handler methods in Servlet environments.

    - If the method parameter is Map<String, String> or MultiValueMap<String, String> then the map is populated with all path variable names and values.

    翻译过来就是:

    - 在SpringMVC中可以使用@PathVariable注解,来支持绑定URL模板参数(占位符参数/参数带值)

    - 另外如果controller的参数是Map(String, String)或者MultiValueMap(String, String),也会顺带把@PathVariable的参数也接收进去

    @PathVariable的RESTful示范

    前面讲作用的时候已经有一个,现在再提供多一个,别人访问的时候可以http://localhost:8080/call/窗口号-检查编号-1

    /**
       * 叫号
       */
      @PutMapping("/call/{checkWicket}-{checkNum}-{status}")
      public ApiReturnObject call(@PathVariable("checkWicket") String checkWicket,@PathVariable("checkNum") String checkNum,
          @PathVariable("status") String status) {
        if(StringUtils.isBlank(checkWicket) || StringUtils.isBlank(checkNum)) {
          return ApiReturnUtil.error("叫号失败,窗口号,检查者编号不能为空");
        }else {
          if(StringUtils.isBlank(status)) status ="1";
          try {
            lineService.updateCall(checkWicket,checkNum,status);
            return ApiReturnUtil.success("叫号成功");
          } catch (Exception e) {
            return ApiReturnUtil.error(e.getMessage());
          }
        }
      }

    补充:解决@PathVariable接收参数带点号时只截取点号前的数据的问题

    问题:

    @RequestMapping(value = "preview/{fileName}", method = RequestMethod.GET)
    public void previewFile(@PathVariable("fileName") String fileName, HttpServletRequest req, HttpServletResponse res) {
     officeOnlinePreviewService.previewFile(fileName, req, res);
    }

    本来fileName参数传的是:userinfo.docx,

    但结果接收到的是:userinfo

    这显然不是我想要的。

    解决方法:

    @RequestMapping(value = "preview/{fileName:.+}", method = RequestMethod.GET)
    public void previewFile(@PathVariable("fileName") String fileName, HttpServletRequest req, HttpServletResponse res) {
     officeOnlinePreviewService.previewFile(fileName, req, res);
    }

    参数fileName这样写,表示任何点(包括最后一个点)都将被视为参数的一部分:

    {fileName:.+}
    

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持IIS7站长之家博文。如有错误或未考虑完全的地方,望不吝赐教。