【问题标题】:@RequestMapping with parameter in the middle of path@RequestMapping 在路径中间带有参数
【发布时间】:2014-09-20 16:06:17
【问题描述】:

假设我在以下 URL 显示 id = 1 的学术小组的日程安排:http://localhost:8222/schedule?groupId=1

在此页面上,我有用于从日程表中删除特定课程的按钮。 JSP 中按钮的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;
}

但这不起作用,这个方法永远不会被调用。如何正确编写此方法以实现我想要实现的目标?

【问题讨论】:

  • 不,那个 URL 没有任何意义。查询字符串出现在末尾,而不是中间。创建一些更安静的东西,比如/schedule/1/lesson/1,然后发送 DELETE 请求来删除它。

标签: java spring jsp url spring-mvc


【解决方案1】:

?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;
 }

要了解更多信息:

【讨论】:

    猜你喜欢
    • 2016-10-20
    • 2021-05-04
    • 2012-11-09
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 2020-02-17
    相关资源
    最近更新 更多