簡體   English   中英

如何讓 Spring 只看到添加到 url 的最后一個路徑變量?

[英]How to make Spring see only the last path variable added to 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");
        }
    }

如果你只想要路徑變量中的最后一個 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

讓我知道這是否有幫助。

例如,也許您在 HTML 表格中使用了錯誤的 url ...

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

確保您的 URL 是正確的。 它應該是

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM