在Java-Jersey中,可以接收资源的动态路径,例如
本地主机:8080 / web服务/这个/是/我的/动态/路径
@GET
@Path("{dynamicpath : .+}")
@Produces(MediaType.APPLICATION_JSON)
public String get(@PathParam("dynamicpath") String p_dynamicpath) {
return p_dynamicpath;
}
打印出:这/是/ my / dynamic / path
问题:如何在Spring MVC中执行此操作?
答案 0 :(得分: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;
}
如果要查看浏览器中返回的String,则还需要声明方法@ResponseBody
(因此返回的String是响应的内容):
@RequestMapping(value="/**", method = RequestMethod.GET, produces = "text/plain")
@ResponseBody
public String get(HttpServletRequest request) throws Exception {