假设我在以下 URL 上显示 id = 1 的学术团体的日程安排:http://localhost:8222/schedule?groupId=1
。
在此页面上,我有用于从时间表中删除特定类(class)的按钮。 JSP中Button的action
属性有如下值:"schedule?${pageContext.request.queryString}/delete/${lessons[count].id}"
,所以单击 id = 1 类(class)附近的“删除”按钮会导致重定向到此 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
和 lesson 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;
}
了解更多:
关于java - @RequestMapping 参数在路径中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25950686/