【问题标题】:How to make Spring see only the last path variable added to url?如何让 Spring 只看到添加到 url 的最后一个路径变量?
【发布时间】:2021-01-14 03:46:12
【问题描述】:

我只想为 /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");
        }
    }

【问题讨论】:

  • 看起来您在表单中使用了错误的路径 URL 或您调用 @GetMapping("/show-owner/{id}") 的链接。你能告诉我你从哪里调用 URL /show-owner/{id} 的 HTML 代码。

标签: java spring model-view-controller


【解决方案1】:

也许您在 HTML 表单中使用了错误的 url 比如……

<form action="show-owner/{id}">

确保您的网址正确无误。应该是

<form action="/show-owner/{id}">

【讨论】:

    【解决方案2】:

    如果你只想要路径变量的最后一个 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
    

    如果这有帮助,请告诉我。

    【讨论】:

    • 这不是我的意思。我不想拿到身份证。我只是不想在每次更改时都指定 url 并让我的 getter 使用这样的单个映射值。 @GetMapping("/show-owner/{id}")
    • 好的,那么我将为此编辑我的答案
    猜你喜欢
    • 1970-01-01
    • 2014-03-17
    • 2021-12-06
    • 2020-07-06
    • 2011-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-28
    相关资源
    最近更新 更多