【问题标题】:Cannot handle request by requestMapping无法通过 requestMapping 处理请求
【发布时间】:2015-09-25 19:40:33
【问题描述】:

我需要处理类似的请求

www.example.com/student/thisisname?age=23&country=UK&city=London

我只对thisisname 部分和city 参数的值感兴趣。

我有以下 RequestMapping 但它不起作用。我也试过{name}{.*:city}

@RequestMapping(value = "/{name:.*}{city}", method = RequestMethod.GET)

【问题讨论】:

  • city=London 是一个查询参数。使用 @RequestParam 带注释的方法参数。
  • 你可以去@PathVariable,看看这个网址stackoverflow.com/questions/19803731/spring-mvc-pathvariable
  • 使用@PathVariable注解的方法参数。每当您使用 GET 方法在 URL 中传递参数时,请使用 @PathVariable 注释来获取它
  • 您确定将学生姓名作为路径变量有意义吗?学生证不是更好吗?

标签: java spring spring-mvc annotations


【解决方案1】:

您可以使用 PathVariable 和 RequestParam 注释来处理它。在下面的代码名称是thisisname部分,城市是查询参数城市值。

@RequestMapping(value = "/student/{name}", method = RequestMethod.GET)
public void someMethod(@PathVariable String name, @RequestParam("city") String city){

}

【讨论】:

  • 返回QueryParam的代码无法解析为类型
  • @DanielNewtown 你必须添加 jsr311-api 依赖才能获取 QueryParam
  • @QueryParam 是一个 JAX-RS 注释。他们正在使用 Spring MVC,它不提供 JAX-RS 的实现。
  • @SotiriosDelimanolis 实际上你可以同时使用 spring-mvc 和 JAX-RS。无论如何,我已经编辑了我的答案并将 QueryParam 替换为 RequestParam
  • 不,您可以将 Spring 与 JAX-RS 一起使用。 Spring MVC 是它自己的堆栈。
【解决方案2】:

您可以通过 2 种方式做到这一点。使用@RequestParam 或@PathVariable

  1. 通过使用@RequestParam
@RequestMapping(value = "/name", method = RequestMethod.GET)
public void someMethod(@RequestParam String city){}
  1. 通过使用@PathVariable
@RequestMapping(value = "/name/{city}", method = RequestMethod.GET)
public void someMethod(@PathVariable String city){}

您可以使用任何一种方法,只需要专注于 URL

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 2013-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-28
    • 1970-01-01
    相关资源
    最近更新 更多