好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

spring mvc中@PathVariable / 带斜杠方式获取

spring mvc @PathVariable / 带斜杠方式获取

遇上这个问题,百度google了一下,抄袭里面的内容,可以实现,在此备忘

实例

?

1

2

3

4

@RequestMapping (value = "/download/{value1}/**" , method = RequestMethod.GET)

public void getValue( @PathVariable String value1, HttpServletRequest request) throws CommonException {

String value = extractPathFromPattern(request);

}

?

1

2

3

4

5

private String extractPathFromPattern( final HttpServletRequest request) {

String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);

String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);

return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);

}

springMVC @PathVariable中间带/问题处理

问题

请求地址/username/resourceUrl/methodName,其中username可能有也可能没有,resourceUrl中会带/,这个时候要使用@PathVariable,不能正确匹配controller

解决思路

把resourceUrl处理成一个不带/的参数即可

1、约定好/替换方案,比如请求方把/全部替换为--

2、通过url编码解码处理 / 经过编码变成%2F 把resourceUrl编码后,这个时候发现还是不能请求到正确的方法,因为到spring时已经自动解码了。可以把%2F再编一次码变成%252F。%编码后是25

?

1

2

3

4

5

6

7

/**

*/ abc/xiaoming/h5/user.json/get

*/

@ResponseBody

     @RequestMapping (method=RequestMethod.POST ,value= "/abc/{username}/{resourceUrl}/{methodName}" )

     public String dubboMock(HttpServletResponse response, @PathVariable String username, @PathVariable String resourceUrl, @PathVariable String methodName){

     }

3、放弃使用PathVariable,手动去处理

?

1

2

3

4

5

6

7

8

9

/**

*/ abc/xiaoming/h5/user.json/get

*/

@ResponseBody

     @RequestMapping (method=RequestMethod.POST ,value= "/abc/**" )

     public String dubboMock(HttpServletResponse response,HttpServletResponse request){

  String url = request.getRequestURI();

         //处理url

     }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/jiangxuexuanshuang/article/details/51720362

查看更多关于spring mvc中@PathVariable / 带斜杠方式获取的详细内容...

  阅读:25次