💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
对于异步请求,前后端最常用的就是 json 字符串。处理 json 字符串有多种框架,下面介绍基于fastjson 工具实现的 FastJsonHttpMessageConverter 消息转换器来处理 json 数据。 <br/> 步骤如下: **1. 引入 fastjson 依赖** ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.80</version> </dependency> ``` **2. 在`resources/springmvc-servlet.xml`配置FastJsonHttpMessageConverter** ```xml <mvc:annotation-driven> <mvc:message-converters> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <!-- 设置编码格式,防止中文乱码 --> <value>text/html;charset=UTF-8</value> <!-- 设置响应的数据格式 --> <value>application/json</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> ``` **3. controller层代码** ```java @Controller public class AsyncController { @ResponseBody @PostMapping(value = "/v2/async/student") public Student getMessage(Student student) { //Student(name=张三, age=25, gender=男生) System.out.println(student); return student; } } ``` **4. 创建一个实体类来对应前端的json字符串** ```java @Data public class Student { private String name; private Integer age; private String gender; } ``` **5. 前端发送json字符串** ```html <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $.ajax({ async: true, type: 'post', url: '${pageContext.request.contextPath}/v2/async/student', data: {'name': '张三', 'age': 25, 'gender': '男生'}, dataType: 'json', beforeSend: function () { }, success: function (data) { console.log(data) //{age: 25, gender: '男生', name: '张三'} }, error: function (data) { } }) </script> ```