spring boot 支持jsonp请求

spring boot 支持jsonp请求

项目中有用到 jsonp请求,那怎么使用spring boot 实现呢

实现

在不改动原有的框架基础上,对jsonp响应单独处理,即 实现 AbstractHttpMessageConverter:

java 复制代码
public class JsonpHttpMessageConverter extends AbstractHttpMessageConverter<Object> {

    private final ObjectMapper objectMapper;

    public JsonpHttpMessageConverter(ObjectMapper objectMapper) {
        super(new MediaType("application", "javascript", StandardCharsets.UTF_8));
        this.objectMapper = objectMapper;
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        // 这里可以限制哪些类型的对象可以被序列化为 JSONP
        //响应的数据类型
        return JsonpController.DataM.class.isAssignableFrom(clazz);
    }

    @Override
    protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        throw new UnsupportedOperationException("Reading is not supported");
    }

    @Override
    protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        HttpServletRequest currentHttpRequest = getCurrentHttpRequest();
        String jsonpCallback = currentHttpRequest.getParameter("callback");
        if (jsonpCallback == null || jsonpCallback.isEmpty()) {
            // 如果没有提供回调函数,则默认返回 JSON
            objectMapper.writeValue(outputMessage.getBody(), object);
        } else {
            // 获取请求参数中的 callback 参数值
            String callbackParam = jsonpCallback; // 实际应用中应该从请求对象中获取
            outputMessage.getBody().write((callbackParam + "(").getBytes(StandardCharsets.UTF_8));
            objectMapper.writeValue(outputMessage.getBody(), object);
            outputMessage.getBody().write(");".getBytes(StandardCharsets.UTF_8));
        }
    }

    public static HttpServletRequest getCurrentHttpRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes != null) {
            return servletRequestAttributes.getRequest();
        }
        return null; // 或者抛出异常,取决于你的需求
    }
}

加入配置

java 复制代码
@Configuration
public class WebConfig implements WebMvcConfigurer {

    private final ObjectMapper objectMapper;

    public WebConfig(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(0, new JsonpHttpMessageConverter(objectMapper));
    }
}

测试:

java 复制代码
@RestController
public class UserController {

    @GetMapping("/index")
    public UserDto index(){
        UserDto user = new UserDto();
        user.setStartTime(LocalDateTime.now());
        return user;
    }

    @GetMapping("/test/data")
    public JsonpController.DataM getData(@RequestParam(value = "callback", required = false) String callback,
                          HttpServletRequest request) throws IOException {
        JsonpController.DataM data = new JsonpController.DataM(); // 初始化你的数据对象
        data.setKey("a");
        data.setValue("b");
        return data;
    }
}

请求jsonp, http://localhost:8080/test/data?callback=callback:

bash 复制代码
# 响应类型为 text/plain
callback({"key":"a","value":"b"}

如果不带 callback:

bash 复制代码
# 响应类型为 text/plain
{"key":"a","value":"b"}
相关推荐
William Dawson5 小时前
Spring Boot 接入华为 MRS ClickHouse(JDBC + 安全认证 + 负载均衡)实战
spring boot·redis·华为
摇滚侠13 小时前
《SpringBoot 3:入门与应用实战》第 12 章 JDBC 与事务 使用 JdbcTemplate 阅读笔记 32
spring boot·笔记·后端
卓怡学长21 小时前
w210基于springboot反诈平台设计与实现
java·spring boot·spring·intellij-idea
大模型丫丫1 天前
如何提升单体 Spring Boot 应用的并发数?
java·spring boot·后端
RuoyiOffice1 天前
SpringBoot3+Vue3 最推荐的开源 OA 系统 2026:流程驱动、资源闭环、多端互通
spring boot·vue3·flowable·oa·协同办公·spring boot 3·开源oa
计算机毕设定制辅导-无忧学长1 天前
基于Spring Boot的玄幻小说个性化推荐平台设计与实现
java·vue.js·spring boot·后端·mysql·推荐算法
Harry Lei1 天前
长期记忆系统的设计与实现
spring boot·postgresql·embedding
卓怡学长1 天前
w156一周穿搭App的设计与实现
java·spring boot·spring·maven·intellij-idea
步行cgn1 天前
Spring Boot 绑定简单 Bean 详解
java·spring boot·后端
爱折腾的编程老炮1 天前
潮玩品牌自建抽盒机小程序——商城 + 抽盒 + 一番赏 + 会员 + 社区,一套代码怎么搭
spring boot·小程序·vue·mybatis·uniapp