java 获取URI路径中的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1536863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 16:59:51  来源:igfitidea点击:

Get the variable in the path of a URI

javaspring-mvccontroller

提问by flybywire

In Spring MVC I have a controller that listens to all requests coming to /my/app/path/controller/*.

在 Spring MVC 中,我有一个控制器来监听所有来自/my/app/path/controller/*.

Let's say a request comes to /my/app/path/controller/blah/blah/blah/1/2/3.

假设一个请求来到/my/app/path/controller/blah/blah/blah/1/2/3.

How do I get the /blah/blah/blah/1/2/3part, i.e. the part that matches the *in the handler mapping definition.

我如何获取/blah/blah/blah/1/2/3部分,即与*处理程序映射定义中的匹配的部分。

In other words, I am looking for something similar that pathInfodoes for servlets but for controllers.

换句话说,我正在寻找与pathInfoservlet相似但适用于控制器的东西。

采纳答案by labratmatt

In Spring 3 you can use the @ PathVariable annotation to grab parts of the URL.

在 Spring 3 中,您可以使用 @PathVariable 注释来获取 URL 的一部分。

Here's a quick example from http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/

这是来自http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/的一个快速示例

@RequestMapping(value="/hotels/{hotel}/bookings/{booking}", method=RequestMethod.GET)
public String getBooking(@PathVariable("hotel") long hotelId, @PathVariable("booking") long bookingId, Model model) {
    Hotel hotel = hotelService.getHotel(hotelId);
    Booking booking = hotel.getBooking(bookingId);
    model.addAttribute("booking", booking);
    return "booking";
}

回答by Dónal Boyle

In Spring 2.5 you can override any method that takes an instance of HttpServletRequest as an argument.

在 Spring 2.5 中,您可以覆盖任何将 HttpServletRequest 实例作为参数的方法。

org.springframework.web.servlet.mvc.AbstractController.handleRequest

org.springframework.web.servlet.mvc.AbstractController.handleRequest

In Spring 3 you can add a HttpServletRequest argument to your controller method and spring will automatically bind the request to it. e.g.

在 Spring 3 中,您可以向控制器方法添加 HttpServletRequest 参数,spring 将自动将请求绑定到它。例如

    @RequestMapping(method = RequestMethod.GET)
    public ModelMap doSomething( HttpServletRequest request) { ... }

In either case, this object is the same request object you work with in a servlet, including the getPathInfo method.

在任一情况下,此对象与您在 servlet 中使用的请求对象相同,包括 getPathInfo 方法。