如何让 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}">
我只想为 /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}">