【问题标题】:Spring Rest and JSONP conversion errorSpring Rest 和 JSONP 转换错误
【发布时间】:2016-06-06 10:18:42
【问题描述】:

我正在尝试将我的所有 Spring REST API 的响应转换为 JSONP。我尝试了以下 URL:

Spring Rest and Jsonp

为自定义 bean 生成 JSONP(例如:Employee Bean)。但不适用于字符串和 int(原始类型)。我应该添加任何其他依赖项还是应该检查所有请求数据类型并应用转换?

例如。 URL http://localhost:8080/demo2?callback=test 应该返回 test("demo2") 但只返回 demo2。

http://localhost:8080/demo?callback=test 正确返回 test({"attr":"demo"});

另外,如果我从 URL 接受 int 并返回相同的值,则会生成 JSONP。但不适用于方法内部的 int 集。

不工作:localhost:8080/demo2?callback=test

@RequestMapping(produces = APPLICATION_JSON_VALUE)
Integer demo2() {
    int i=3;
    return i;
}

抛出错误:此请求标识的资源只能生成具有根据请求“接受”标头不可接受的特征的响应。工作:localhost:8080/demo2/3?callback=test

 @RequestMapping(value="test/{a}" produces = APPLICATION_JSON_VALUE)
Integer demo2 (@PathVariable("a")int a)
{
       return a;
}

测试(3);

【问题讨论】:

  • 请解释一些合乎逻辑的事情..实际上我没有明白你想说什么..你提到了两个code,但没有定义你到底想要实现什么?完全混乱..
  • 我的问题是关于/延续我在开头发布的 URL。如果您不阅读它,您将无法理解我的问题,显然它看起来很混乱,从您的角度来看它看起来不合逻辑。

标签: java spring rest jsonp


【解决方案1】:

改成

@RequestMapping(value = "/test/{a}", produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Integer demo2(@PathVariable("a") int a) {
    return a;
}

并确保你有

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.0</version>
</dependency>

在你的 pom 中。

【讨论】:

  • 感谢您的回复。它在我的 pom 中。我试过你的建议。我得到相同的“此请求标识的资源只能生成具有根据请求“接受”标头不可接受的特征的响应。”错误信息。
  • 嗨,这种方法可以正常工作,我在我的问题中提到过“工作”。但是下面的这种方法会引发错误。 @RequestMapping(produces = APPLICATION_JSON_VALUE) 整数 demo2() { int i=3;返回我; }
  • 那个方法没有URL映射??
  • 一切都在那里。我的实际代码:@RequestMapping(value="/Test5.html", method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) public ResponseEntity getTest5(){ Integer a=6;返回 ResponseEntity.accepted().body(a); }
  • 另一个同样不起作用的代码:@RequestMapping(value="/Test3.html", method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) @ResponseBody int getTest3(){ int a =9;返回一个; }
猜你喜欢
  • 1970-01-01
  • 2019-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多