@参数位于路径中间的RequestMapping



假设我正在以下URL显示id为1的学术小组的时间表:http://localhost:8222/schedule?groupId=1

在这个页面上,我有从时间表中删除特定课程的按钮。JSP中Button的action属性具有以下值:"schedule?${pageContext.request.queryString}/delete/${lessons[count].id}",因此单击id为1的课程附近的"删除"按钮会导致重定向到此URL:http://localhost:8222/schedule?groupId=1/delete/1

我想做的是创建一个映射到此URL的方法,该方法执行删除并重定向到具有当前所选组的时间表的页面:http://localhost:8222/schedule?groupId=1。以下是我尝试做的:

@RequestMapping(value = "/schedule?groupId={groupId}/delete/{lessonId}")
public String deleteLesson(@PathVariable("lessonId") Integer lessonId, @PathVariable("groupId") Integer groupId) {
    lessonRepository.delete(lessonId);
    return "redirect:/schedule?groupId=" + groupId;
}

但这不起作用,此方法从未被调用。我如何正确地为我试图实现的目标编写这种方法?

像使用?groupId这样的groupId之后,groupId将成为一个参数,URL的后面部分将成为其值。因此,如果你不想改变现有的URL模式,你的请求处理方法应该如下:

@RequestMapping(value = "/schedule")
public String deleteLesson(@RequestParam("groupId") String restOfTheUrl) {
  log.info(restOfTheUrl);
  // your code
}

记录后,您应该看到,例如:

 1/delete/2

现在,您必须解析它以获得groupId,并解析课程id以进行删除。

但如果你想用自己的方式处理它,你的代码应该是这样的:

 @RequestMapping(value = "/schedule/groupId/{groupId}/delete/{lessonId}") // convert you request param to path varriable
 public String deleteLesson(@PathVariable("lessonId") Integer lessonId, @PathVariable("groupId") Integer groupId) {
    lessonRepository.delete(lessonId);
    return "redirect:/schedule?groupId=" + groupId;
 }

了解更多:

  • @PathVariable和@RequestParam之间的差异

最新更新