【问题标题】:How to create the controller for a specific URL [duplicate]如何为特定 URL 创建控制器 [重复]
【发布时间】:2018-09-14 04:10:12
【问题描述】:

我需要从这个网址开始,http://localhost:8080/home/filter?projectId=1;fileId=1

我创建了这个控制器:

@GetMapping("/home/filter/{projectId}/{fileId}")
public String filter(@PathVariable("projectId") int projectId, @PathVariable("fileId") int fileId) {

    System.out.println("Project Id " + projectId);

    System.out.println("File Id " + fileId);

    return "redirect:/home";
}

当我测试时:http://localhost:8080/home/filter?projectId=1;fileId=1 我收到此错误:

 This application has no explicit mapping for /error, so you are seeing this as a fallback.
 Wed Apr 04 17:24:51 EEST 2018
 There was an unexpected error (type=Not Found, status=404).
 /home/filter

我不知道该怎么办..

【问题讨论】:

  • 如果您使用的是 spring boot,那么您肯定正在执行其中之一,请在此处查看。stackoverflow.com/questions/49375500/…
  • 提示:/home/filter?projectId=1;fileId=1 格式不同于 /home/filter/{projectId}/{fileId}
  • 必须是这样的:/home/filter{projectId}{fileId} ??

标签: java spring spring-mvc thymeleaf


【解决方案1】:

您需要了解 URL 中 query 参数和 path 参数之间的区别。

  • 查询参数是?之后的参数,格式为name=value(如果有多个参数,则以&分隔),
    比如http://localhost:8080/home/filter?projectId=1&fileId=1
  • 路径参数由/分隔(如果有,则在?之前),
    比如http://localhost:8080/home/filter/1/1

对于 query 参数,您可以在控制器中使用 @RequestParam 注释。
示例:对于像 http://localhost:8080/home/filter?projectId=1&fileId=1 这样的 URL 您的控制器可能如下所示:

@GetMapping("/home/filter")
public String filter(@RequestParam("projectId") int projectId,  
                     @RequestParam("fileId") int fileId) {
    ...
}

对于 path 参数,您可以在控制器中使用 @PathVariable 注释。
示例:对于像 http://localhost:8080/home/filter/1/1 这样的 URL 控制器可能如下所示:

@GetMapping("/home/filter/{projectId}/{fileId}")
public String filter(@PathVariable("projectId") int projectId,  
                     @PathVariable("fileId") int fileId) {
    ...
}

【讨论】:

  • 注意http://localhost:8080/home/filter?projectId=1;fileId=1http://localhost:8080/home/filter?projectId=1&fileId=1之间的区别
  • @larsgrefer 感谢您的指出。似乎我混淆了查询和矩阵参数。更新了我的答案。
  • 我只是不确定 Spring 是否实现了这个建议:w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.2.2
  • @larsgrefer 我已经测试过 Spring 是否实现了这个建议。而且似乎 Spring 仅通过 & 分隔查询参数,而不是 ;
【解决方案2】:

TL;DR:只需调用正确的 URL:http://localhost:8080/home/filter/1/1

注意路径参数和查询参数的区别。

您的控制器映射使用路径参数,而您调用的 URL 使用查询参数

【讨论】:

猜你喜欢
  • 2012-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-03
  • 2020-10-02
  • 2011-06-23
  • 2016-07-18
  • 2011-04-10
相关资源
最近更新 更多