首页 > 解决方案 > 如何让 Spring 只看到添加到 url 的最后一个路径变量?

问题描述

我只想为 指定获取请求/show-owner/{id},但每次在 URL 中添加另一个路径时,我都会收到 404 not found 错误,我必须提供完整路径才能使其正常工作。

在这种情况下最好的方法是什么?

@GetMapping(value = {"/show-owner/{id}", "/show-item/show-owner/{id}",
            "/show-user/user-items-table/show-item/show-owner/{id}",
            "/show-user/user-items-table/show-item/show-owner/user-items-table/{id}",
    "/show-owner/user-items-table/show-item/show-owner/{id}",
    "/user-items-table/show-item/show-owner/{id}"})
    public ModelAndView displayOwnerByItemId(@PathVariable String id) {
        try {
            UserDto user = userDtoMapper.toDto(itemService.getItemById(id).getOwner());

            ModelAndView mav = new ModelAndView("show-user");
            mav.addObject("user", user);
            return mav;
        } catch (ItemNotFound e) {
            return new ModelAndView("redirect:/items");
        }
    }

标签: javaspringmodel-view-controller

解决方案


如果您只想要路径变量中的最后一个 id,您可以做一件事。您将以逗号分隔的字符串获取 id。所以最简单的解决方案是根据逗号分割字符串并像这样获取最后一个索引的值。

String k[] = id.split(",");
System.out.println(k[k.length-1]);//just to check whether u are getting the last id value or not

让我知道这是否有帮助。


推荐阅读