【问题标题】:Why passing param name is mandatory for RestTemplate in Spring为什么在 Spring 中为 RestTemplate 传递参数名称是强制性的
【发布时间】:2018-01-18 12:19:23
【问题描述】:

我实现了 api

https://theysaidso.com/api/#qod 

使用弹簧休息模板。我的问题是,如果我制作如下所示的网址,它是否有效。但是如果我从括号中删除参数名称,它不会并返回错误。任何想法?谢谢!

这行得通:

QuoteResponse quoteResponse=    
this.restTemplate.getForObject("http://quotes.rest/qod.json?category=
{param}", QuoteResponse.class, category);

这不是

QuoteResponse quoteResponse=    
this.restTemplate.getForObject("http://quotes.rest/qod.json?category={}", 
QuoteResponse.class, category);

我想两者都转换为下面(将值传递作为类别字符串的启发

"http://quotes.rest/qod.json?category=inspire"

更新(添加更多代码):控制器

@Autowired
QuoteService quoteService;

@RequestMapping(value="/ws/quote/daily", produces=MediaType.APPLICATION_JSON_VALUE,method=RequestMethod.GET)
public ResponseEntity<Quote> getDailyQuote(@RequestParam(required=false) String category){
    Quote quote = quoteService.getDaily(category);
    if(quote==null)
        return new ResponseEntity<Quote>(HttpStatus.INTERNAL_SERVER_ERROR);
    return new ResponseEntity<Quote>(quote,HttpStatus.OK);

}

QuoteService.getDaily

@Override
public Quote getDaily(String category){
    if(category==null || category.isEmpty())
        category=QuoteService.CATEGORY_INSPIRATIONAL;
    QuoteResponse quoteResponse=
            this.restTemplate.getForObject("http://quotes.rest/qod.json?category={cat}", 
                    QuoteResponse.class, category);


    return quoteResponse.getContents().getQuotes()[0];      
}

【问题讨论】:

  • 粘贴控制器代码帮助我们调查这个问题。
  • @Lovababu 添加
  • 因为你有“required=false”,spring 不会强迫你传递查询参数。和 category={any_name},这里 {any_name} 只是 RestTemplate 的占位符,它在进行实际的 rest 调用之前用提供的 uriVariable 替换这个占位符。

标签: java spring rest spring-boot resttemplate


【解决方案1】:
this.restTemplate.getForObject("http://quotes.rest/qod.json?category=
{param}", QuoteResponse.class, category); 

当您发出这样的请求时,这意味着您正在将 PathVariable 传递给由控制器参数中的 @PathVariable 注释处理的控制器。

如果控制器上有@PathVariable

PathVariable 是必需的,以便完成您的工作。

restTemplate.getForObject("http://quotes.rest/qod.json?category={}", 
QuoteResponse.class, category); 

当您提出这样的请求时,您没有发送任何 PathVariable 以及此处所需的请求,因此不起作用并抛出 MissingPathVariableException

【讨论】:

  • @谢谢!我假设您的意思是 RequestParameter 不是 PathVariable,因为据我了解,路径变量就像 /quotes.rest/qod.json/{cat} 和 //quotes.rest/qod.json?category={cat} 用于请求参数.但是对于这个问题,RequestParam 应该有一个名字,对吧?而它适用于传递的任何名称,即 this.restTemplate.getForObject("quotes.rest/qod.json?category= {param}", QuoteResponse.class, category).. 有效.. 和 .this 也有效。 this.restTemplate.getForObject("quotes.rest/qod.json?category= {param12345}", QuoteResponse.class, 类别)
猜你喜欢
  • 2018-11-29
  • 1970-01-01
  • 1970-01-01
  • 2016-11-09
  • 1970-01-01
  • 2019-06-11
  • 2018-12-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多