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

网友投稿 284 2022-11-02


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

@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,

@PathVariable的PathVariable官方doc解释

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

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

翻译过来就是:

- 在SpringMVChttp://中可以使用@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,

但结果接收到的是:ushttp://erinfo

这显然不是我想要的。

解决方法:

@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:.+}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:全链路监控工具pinpoint 部署带pinpoint agent的product服务
下一篇:CI流水线中制品库集成 maven编译过后包上传
相关文章

 发表评论

暂时没有评论,来抢沙发吧~