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

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
    }
}

  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"
});

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容