我已经配置了一个应用程序,它根据URL末尾附加的内容返回json和xml视图。
按照:
http://pfelitti87.blogspot.co.uk/2012/07/rest-services-with-spring-3-xml-json.html
我想重新配置它,但只允许返回xml。
不知道如何做到这一点,我所做的一切仍然会返回json,当没有任何内容附加到结尾时
@Bean(name = "viewResolver")
public ContentNegotiatingViewResolver viewResolver() {
ContentNegotiatingViewResolver contentNegotiatingViewResolver = new ContentNegotiatingViewResolver();
contentNegotiatingViewResolver.setOrder(1);
contentNegotiatingViewResolver.setFavorPathExtension(true);
contentNegotiatingViewResolver.setFavorParameter(true);
contentNegotiatingViewResolver.setIgnoreAcceptHeader(false);
Map<String, String> mediaTypes = new HashMap<String, String>();
mediaTypes.put("xml", "application/xml");
contentNegotiatingViewResolver.setMediaTypes(mediaTypes);
List<View> defaultViews = new ArrayList<View>();
defaultViews.add(xmlView());
contentNegotiatingViewResolver.setDefaultViews(defaultViews);
return contentNegotiatingViewResolver;
}
所以输出如下:
.../state.json error no jsp page json
.../state.xml works fine
.../state error no jsp page
我想要的是以下两个返回xml的网址
.../state
.../state.xml
以上不起作用..
这是控制器映射
@RequestMapping(value= "/{id}/{ref}/state", method = RequestMethod.GET)
public state getState(...) {...}
答案 0 :(得分:2)
这是通过xml配置的解决方案; - 控制器
@Controller
@RequestMapping("/simpleEntity")
public class SimpleRestController {
@RequestMapping(method=RequestMethod.GET)
public @ResponseBody SimpleEntity get() {
return new SimpleEntity();
}
}
xml
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="xstream"/>
<property name="unmarshaller" ref="xstream"/>
<property name="supportedMediaTypes">
<list>
<value>#{T(org.springframework.http.MediaType).TEXT_XML_VALUE}</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<context:component-scan base-package="de.incompleteco.spring.web"/>
<bean id="xstream" class="org.springframework.oxm.xstream.XStreamMarshaller"/>
这是配置版
@Configuration
@EnableWebMvc
@ComponentScan("de.incompleteco.spring.web")
public class SimpleConfiguration extends WebMvcConfigurerAdapter {
private XStreamMarshaller marshaller;
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(getHttpMessageConverter());
super.configureMessageConverters(converters);
}
public HttpMessageConverter<Object> getHttpMessageConverter() {
MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter();
converter.setMarshaller(marshaller());
converter.setUnmarshaller(marshaller());
return converter;
}
@Bean
public AbstractMarshaller marshaller() {
if (marshaller == null) {
return new XStreamMarshaller();
} else {
return marshaller;
}
}
}
答案 1 :(得分:0)
尝试以下
从类路径中删除jackson
从<entry key="json" value="application/json" />
的{{1}}删除条目mediaTypes
。
从ContentNegotiatingViewResolver
的{{1}}移除bean <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
。