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"}
相关推荐
用户3521802454751 天前
当 Prompt 学会"热更新":Spring Boot × Nacos3 AI 实战
java·spring boot·ai编程
昵称为空C1 天前
手撸一个动态 SQL 执行引擎:不重启服务,在线增删改查任意数据库
spring boot·后端
霸道流氓气质2 天前
领域驱动设计(DDD)在 Spring Boot 微服务中的实践指南
运维·spring boot·微服务
于先生吖2 天前
SpringBoot对接大模型开发AI命理测算系统:八字排盘与AI解析接口源码全解
人工智能·spring boot·后端
Flittly2 天前
【AgentScope Java新手村系列】(10)实战-多Agent天气助手
java·spring boot·spring
星落zx2 天前
Spring Boot 多模型集成:优雅调用全球主流大模型
人工智能·spring boot·chatgpt
一杯奶茶¥2 天前
水果销售网站 CRM客户信息管理系统 超市管理系 酒店管理系统 健身房管理系统 在线音乐网站 校园招聘系统
java·vue.js·spring boot·mysql·spring·java项目
进阶的小名2 天前
Spring Boot SSE + Nginx 配置:解决 EventSource 不实时返回、连接超时、流式响应被缓冲问题
spring boot·后端·nginx
我登哥MVP2 天前
SpringCloud Alibaba 核心组件解析:服务链路追踪
java·spring boot·后端·spring·spring cloud·java-ee·maven