In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
这篇文章主要讲解了"怎么替换@PathVariable中的变量",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"怎么替换@PathVariable中的变量"吧!
替换@PathVariable的变量
因为要对接口进行统计, 而项目中用到了@PathVariable的注解, 也就是uri中携带请求参数的方式. 导致一个接口统计出来很多个请求, 比如 /api/get/1, /api/get/2 …
在网上找到可以通过
Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
拿到这个PathVariable参数. 于是初步代码如下, 将/api/get/{id} 这个变量替换成常量{x}.
import com.google.common.base.Joiner;import javax.servlet.*; /** * 获取 去除掉 PathVariable 后的uri * @param request * @return */ private String getPureUri(HttpServletRequest request) { String url = request.getRequestURI(); Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); if (pathVariables != null && !pathVariables.isEmpty()){ String[] split = url.split("/"); for (String pathVal : pathVariables.values()) { for (int i = split.length - 1; i >= 0; i--) { if (split[i].equals(pathVal)){ //替换成{x},也可以直接替换成""去掉 split[i] = "{x}"; break; } } } url = Joiner.on("/").join(split); } return url; }@pathvariable注解的使用
带占位符的 URL 是 Spring3.0 新增的功能,该功能在SpringMVC 向 REST 目标挺进发展过程中具有里程碑的意义。
通过 @PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中:URL 中的 {xxx} 占位符可以通过
@PathVariable("xxx") 绑定到操作方法的入参中。
//@GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写 @GetMapping("/getUserById/{id}") public User getUser(@PathVariable("id") Long userId){ return userService.selectUserById(userId); }
不需要使用问号传参,不需要写key=valuel,直接写value即可.
若方法参数名称和需要绑定的uri template中变量名称一致时,可以简写:
//@GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。 @GetMapping("/getUserByName/{userName}") public User getUserByName(@PathVariable String userName){ return userService.selectUserByUserName(userName); }
感谢各位的阅读,以上就是"怎么替换@PathVariable中的变量"的内容了,经过本文的学习后,相信大家对怎么替换@PathVariable中的变量这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.