Spring boot 实现json和jsonp格式数据接口
1.新建一个类继承AbstractJsonpResponseBodyAdvice,重写父类构造方法,
传入callback和jsonp参数。
package com.alibaba.sinfo.h5.agent.advice;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice;
/**
* Created by Jack on 2017/5/31.
*/
@ControllerAdvice
public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {
public JsonpAdvice() {
super("callback", "jsonp");
}
}
2.写返回json和jsonp格式数据的Controller
package com.alibaba.sinfo.h5.agent.controller
import com.alibaba.fastjson.JSONObject
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
import java.text.SimpleDateFormat
/**
* Created by jack on 2017/5/19.
*/
@RestController
class HelloWorld {
@GetMapping("/hello")
def helloWorld(){
JSONObject object = new JSONObject()
object.put("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
object
}
}
- 测试输出
//http://localhost:8500/hello
{
time: "2017-05-31 22:04:50"
}
// 20170531220604
// http://localhost:8500/hello?callback=hellojsonp
/**/hellojsonp({
"time": "2017-05-31 22:06:03"
});