Spring Boot 实现json和jsonp格式数据接口

来源:互联网 发布:网络主播思瑞和眼镜男 编辑:程序博客网 时间:2024/06/08 12:14

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. */@ControllerAdvicepublic class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {    public JsonpAdvice() {        super("callback", "jsonp");    }}

2.写返回json和jsonp格式数据的Controller

package com.alibaba.sinfo.h5.agent.controllerimport com.alibaba.fastjson.JSONObjectimport org.springframework.web.bind.annotation.GetMappingimport org.springframework.web.bind.annotation.RestControllerimport java.text.SimpleDateFormat/** * Created by jack on 2017/5/19. */@RestControllerclass HelloWorld {    @GetMapping("/hello")    def helloWorld(){        JSONObject object = new JSONObject()        object.put("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))        object    }}
  1. 测试输出
//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"
});

阅读全文
0 0