SpringMVC中资源的动态路径

3
在Java-Jersey中,可以接收到一个动态路径的资源,例如:localhost:8080/webservice/this/is/my/dynamic/path。
@GET
@Path("{dynamicpath : .+}")
@Produces(MediaType.APPLICATION_JSON)     
public String get(@PathParam("dynamicpath") String p_dynamicpath) {
     return p_dynamicpath;
} 

打印出:this/is/my/dynamic/path

问题:在Spring MVC中如何实现?

1个回答

2

对于路径中包含多个项的情况,您可以按以下方式访问动态路径值:

@RequestMapping(value="/**", method = RequestMethod.GET)
public String get(HttpServletRequest request) throws Exception {
    String dynPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    System.out.println("Dynamic Path: " + dynPath );
    return dynPath;
}

如果您预先知道路径变量有多少级,可以将其显式编码,例如:

@RequestMapping(value="/{path1}/{path2}/**", method = RequestMethod.GET)
public String get(@PathVariable("path1") String path1,
          @PathVariable("path2") String path2,
          HttpServletRequest request) throws Exception {
    String dynPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    System.out.println("Dynamic Path: " + dynPath );
    return dynPath;
}

如果您想在浏览器中查看返回的字符串,您需要同样声明@ResponseBody方法(这样您返回的字符串就是响应内容):
@RequestMapping(value="/**", method = RequestMethod.GET, produces = "text/plain")
@ResponseBody
public String get(HttpServletRequest request) throws Exception {

谢谢!现在,由于某些原因,我的Web应用程序更改为WEB-INF/jsp/my/entered/path.jsp ... :-) 我猜这一定是配置错误... - user3601578
不,那只是Spring MVC渲染您返回的“视图”(路径字符串)。 - Jan
1
请看我的编辑,了解如何在浏览器中获取字符串响应。 - Jan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接