gpt4 book ai didi

java - spring mvc中资源的动态路径

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:16:00 26 4
gpt4 key购买 nike

在 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 中执行此操作?

最佳答案

对于路径中的多个项目,您可以像这样访问动态路径值:

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

关于java - spring mvc中资源的动态路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35406774/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com