我能够从自定义java对象返回JSONP而没有问题(在此之后:http://www.concretepage.com/spring-4/spring-4-mvc-jsonp-example-with-rest-responsebody-responseentity),但是当我尝试返回带有JSONP的String时,包装函数消失了
我在做什么:
@RequestMapping(value ="/book", produces = {MediaType.APPLICATION_JSON_VALUE, "application/javascript"})
public @ResponseBody ResponseEntity<String> bookInfo() {
JSONObject test = new JSONObject();
test.put("uno", "uno");
return new ResponseEntity<String>(test.toString(), HttpStatus.OK);
}
致电服务:
http://<server>:port//book?callback=test
返回:
{"uno":"uno"}
预期结果:
test({"uno":"uno"})
还试图直接返回JSONObject ResponseEntity.accepted().body(test);
,但我得到了406错误。有什么想法吗?
答案 0 :(得分:1)
错误看起来像this example中的类JsonpAdvice
,不适用于请求映射。
@ControllerAdvice
public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {
public JsonpAdvice() {
super("callback");
}
}
我使用了HashMap,因为它在这里有类似的用法,在这个例子中使用HashMap更简单:
@RequestMapping(value="/book", produces=MediaType.APPLICATION_JSON)
public ResponseEntity<Map> bookInfo() {
Map test = new HashMap();
test.put("uno", "uno");
return ResponseEntity.accepted().body(test);
}
这为我提供了结果:
// http://localhost:8080/book?callback=test
/**/test({
"uno": "uno"
});
我使用的是Spring启动:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0</version>
</dependency>
</dependencies>