您的位置:首页 > 编程语言 > Java开发

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

2017-09-13 14:32 686 查看

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"
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: