SpringMVC信息转换--处理XML和JSON

本文介绍了SpringMVC如何处理XML和JSON格式的请求与响应。通过在Spring WEB容器中配置合适的HttpMessageConverter,并设置请求的Accept头,SpringMVC能实现服务器与客户端之间XML和JSON格式的数据透明通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringMVC提供了几个处理XML和JSON格式的请求/响应信息的HttpMessageConverter:
这里写图片描述
只要在Spring WEB容器中为RequestMappingHandlerAdapter装配好相应的处理XML和JSON格式的请求/响应消息的HttpMessageConverter,并在交互中通过请求的Accept指定MIME类型,SpringMVC就可以使用服务器端的处理方法和客户端透明的通过XML和JSON格式的消息进行通信。

一、在WEB上下文中装配处理XML和JSON格式的请求/响应消息的HttpMessageConverter。
1.1、需要用到的jar包

  <dependency>
      <groupId>com.thoughtworks.xstream</groupId>
      <artifactId>xstream</artifactId>
      <version>1.4.10</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-oxm</artifactId>
      <version>4.3.10.RELEASE</version>
    </dependency>

1.2、web上下文中的配置

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"
          p:messageConverters-ref="messageConverters"/>


    <util:list id="messageConverters">
        <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
        <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
        <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
        <bean class="org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter"/>
<!--装配解析XML和JSON的HttpMessageConverter-->
        <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter"
              p:marshaller-ref="xmlMarshaller"
              p:unmarshaller-ref="xmlMarshaller"/>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>

    </util:list>

    <bean id="xmlMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
        <property name="streamDriver">
            <bean class="com.thoughtworks.xstream.io.xml.StaxDriver"/>
        </property>
        <property name="annotatedClasses">
            <list>
                <!--需要被绑定信息的类-->
                <value>com.smart.bean.User</value>
            </list>
        </property>
    </bean>

(待定)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值