2
@RequestMapping(method = RequestMethod.GET, produces = "application/xml")
@ResponseBody

像这样的响应xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xml>
    <code>0</code>
    <msg>success</msg>
</xml>

但是我想要这样的回应

<xml>
    <code>0</code>
    <msg>success</msg>
</xml>

如何通过注释或 XML 配置文件删除 XML 标头?谢谢。

我已经解决了这个问题

  1. 使用这个 XML Conventor

       <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
            <property name="marshaller" ref="marshaller"></property>
            <property name="unmarshaller" ref="marshaller"></property>
        </bean>
    
  2. 配置 Marshaller bean

    <bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller" id="marshaller">
    <property name="classesToBeBound">
        <list>
            <value>com.xx.entity.Message</value>
        </list>
    </property>
    <property name="marshallerProperties">
        <map>
            <entry>
                <key>
                    <util:constant static-field="javax.xml.bind.Marshaller.JAXB_FRAGMENT"/>
                </key>
                <value type="java.lang.Boolean">true</value>
            </entry>
        </map>
    </property>
    

4

2 回答 2

5

我已经解决了这个问题

  1. 使用这个 XML Conventor

       <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
            <property name="marshaller" ref="marshaller"></property>
            <property name="unmarshaller" ref="marshaller"></property>
        </bean>
    
  2. 配置 Marshaller bean

    <bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller" id="marshaller">
    <property name="classesToBeBound">
        <list>
            <value>com.xx.entity.Message</value>
        </list>
    </property>
    <property name="marshallerProperties">
        <map>
            <entry>
                <key>
                    <util:constant static-field="javax.xml.bind.Marshaller.JAXB_FRAGMENT"/>
                </key>
                <value type="java.lang.Boolean">true</value>
            </entry>
        </map>
    </property>
    

于 2013-08-12T13:22:34.193 回答
0

在 Spring Boot 中,您可以创建自己的子类Jaxb2RootElementHttpMessageConverter并自定义编组器:

@Configuration
class XmlConfiguration {
    @Bean
    Jaxb2RootElementHttpMessageConverter jaxb2RootElementHttpMessageConverter() {
        return new Jaxb2RootElementHttpMessageConverter() {
            @Override
            @SneakyThrows
            protected void customizeMarshaller(Marshaller marshaller) {
                marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
            }
        };
    }
}

@SneakyThrows来自龙目岛)

于 2021-10-13T06:30:16.280 回答