首页 > 解决方案 > 我如何在带有@GetMapping的控制器中使用不同的url和相同的方法?

问题描述

它无法在两个 URL 上运行

@GetMapping(value= {"/durationtrend/{moduleId}","/durationtrend/{moduleId}/{records}"},produces=MediaType.APPLICATION_JSON_VALUE)
public List<ExecutionDurationResource> getExecutionDurationByModuleId(@PathVariable("moduleId") Integer moduleId,@PathVariable("records") Integer records) {    
    return executionDurationService.getExecutionDuration(moduleId,records); 
}

http://localhost:8080/seleniumexecutiontrending/reports/durationtrend/427 --> 它不调用。 http://localhost:8080/seleniumexecutiontrending/reports/durationtrend/427/7-- >它执行。

我想以相同的方法执行两者

标签: spring-mvcget-mapping

解决方案


你的问题是

@PathVariable("moduleId") Integer moduleId,@PathVariable("records") Integer records

您的 URL 都需要moduleIdrecords参数,在第一个 URL 中"/durationtrend/{moduleId}"您没有 records 参数,这就是您拥有的原因

org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException Resolved [org.springframework.web.bind.MissingPathVariableException:缺少整数类型的方法参数的 URI 模板变量“记录”]

这个错误

实际上,您可以通过多种方式实现此目标,例如使用 HttpServletRequest 和其他东西,但请记住您使用的是 spring,您需要使用 spring 框架来简化这些事情。

我建议的简单方法是使用两个单独的控制器并简化事情。

@GetMapping("/durationtrend/{moduleId}")
public void getExecutionDurationByModuleId(@PathVariable("moduleId") Integer moduleId) {
    return executionDurationService.getExecutionDuration(moduleId);
    System.out.println(moduleId);
}

@GetMapping("/durationtrend/{moduleId}/{records}")
public void getExecutionDurationByRecords(@PathVariable("moduleId") Integer moduleId, @PathVariable("records") Integer records) {
    return executionDurationService.getExecutionDuration(moduleId, records);
    System.out.println(moduleId);
    System.out.println(records);
}

这很容易理解,您可以在服务类中创建 getExecutionDuration(moduleId) 方法并轻松绕过它......

希望对您有所帮助...


推荐阅读