获取URI路径中的变量

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取URI路径中的变量相关的知识,希望对你有一定的参考价值。

在Spring MVC中,我有一个控制器,可以监听所有来到/my/app/path/controller/*的请求。

让我们说一个请求来到/my/app/path/controller/blah/blah/blah/1/2/3

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

换句话说,我正在寻找类似pathInfo为servlet做的事情,但是对于控制器。

答案

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

这是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";
}
另一答案

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

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

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

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

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

以上是关于获取URI路径中的变量的主要内容,如果未能解决你的问题,请参考以下文章

如何从Android片段中的相机获取图像

springboot开启矩阵传参MatrixVariable

如何从android pie中的内容uri获取文件路径

使用 Spring mockMvc 测试可选路径变量

获取存储在 sd 卡 + android 中的图像的缩略图 Uri/路径

如何从 Uri xamarin android 获取实际路径