ajax获取数据的3种方式和springmvc消息转换器

来源:互联网 发布:sql去掉重复字段 编辑:程序博客网 时间:2024/06/18 08:19
controller层:


1.ajax获取数据的最原始方式:

传入参数 OutputStream os
os.write(通过第三方json-lib转换的json字符串.getByte())

@RequestMapping(value = "/queryAFood", method = RequestMethod.GET)
public String queryFoodList(OutputStream outputStream, String foodName)
throws Exception {
List<Map<String, Object>> queryFoodList = ajaxFoodService
.queryFoodList(foodName);


JSONArray jsonArray = JSONArray.fromObject(queryFoodList);
String jString = jsonArray.toString();


outputStream.write(jString.getBytes("UTF-8"));
return null;
}

2. 直接返回 字节数组 + @ResponseBody 注解
   减少流的输出动作代码
   os.write(jsonStr.getBytes("UTF-8"));


@ResponseBody
@RequestMapping(value = "/queryAFoodByte", method = RequestMethod.GET)
public byte[] queryFoodByte(OutputStream outputStream, String foodName)
throws Exception {
List<Map<String, Object>> queryFoodList = ajaxFoodService
.queryFoodList(foodName);


JSONArray jsonArray = JSONArray.fromObject(queryFoodList);
String jString = jsonArray.toString();


return jString.getBytes("UTF-8");
}

3. 直接返回对象 springmvc自动转换成json:需要配置消息转换器,引入jar包


@ResponseBody
@RequestMapping(value = "/queryAFoodList", method = RequestMethod.GET)
public List<Map<String, Object>> queryFoodList(OutputStream outputStream, String foodName)
throws Exception {
List<Map<String, Object>> queryFoodList = ajaxFoodService
.queryFoodList(foodName);
return queryFoodList;
}

jar包依赖:
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.6.0</version>
</dependency>
<dependency>
  <groupId>org.codehaus.jackson</groupId>
  <artifactId>jackson-core-asl</artifactId>
  <version>1.9.12</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>2.6.0</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.6.0</version>
</dependency>
<dependency>
  <groupId>org.codehaus.jackson</groupId>
  <artifactId>jackson-mapper-asl</artifactId>
  <version>1.9.12</version>
</dependency>

配置消息转换器 xx-servlet.xml中添加:
  <mvc:annotation-driven >
    <mvc:message-converters>
<!-- 配置返回byte[]的消息转换器 -->
        <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter">
          <property name="supportedMediaTypes">
    <list>
    <value>text/html</value>
    <value>application/x-www-form-urlencoded</value>
    </list>
    </property>
        </bean>

        <!-- 配置返回对应解析成json的消息转换器 -->
    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    <property name="supportedMediaTypes">
    <list>
    <value>text/html</value>
    <value>application/x-www-form-urlencoded</value>
    </list>
    </property>
    </bean>
    </mvc:message-converters>
  
  </mvc:annotation-driven>
原创粉丝点击