Spring's Json not being resolved with appropriate response - java

I've tried to have a controller in Spring return a JSON response to no avail using the Jackson classes as recommended with 3.0. I've got the jackson jar files(jackson-core-asl-1.5.5.jar & jackson-mapper-asl-1.5.5.jar) in my class path of course.
As for the appconfig.xml entries, I'm not sure I need these. I've put them in there as a last act of desperation before returning to ol' fashion non-json ajax.
In debug, I watch the controller get the request, return the foo and then, in firebug, get a 406.
The error messages are as follows:
From the logger when set to debug:
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
From the response:
(406) The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ().
My appconfig.xml is here:
<!-- Configures support for #Controllers -->
<mvc:annotation-driven />
<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="html" value="text/html"/>
<entry key="json" value="application/json"/>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
</list>
</property>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"></property>
</bean>
My controller
#RequestMapping(value="foo/bar", method=RequestMethod.GET)
public #ResponseBody foo getFoo(#RequestParam String fooId) {
return new foo(fooId);
}
On the jsp, where the ajax call is made:
function addRow() {
$.getJSON("foo/bar", {
fooId: 1
}, function(data) {
alert("it worked.");
});
}
Let me know if there's any more info that is needed.

Get rid of all Jackson beans, and of the json mapping in the negotiating resolver. the mvc:annotation-driven should configure everything you need for the Jackson serialization to work.

Make sure the POJO you return has get()ers, one for each field.
Make sure the appserver (Tomcat) has the libraries even if you are sure your build system (Eclipse/Maven) does.
I've had this error twice now.
Just now I added getters to my pojo. The 406 error went away and I got JSON as expected.
I assume that because my fields were package-protected (the default access), it would grab them, but I guess not.
For the record, in case it matters, I also made the POJO implement Serializable, toString(), serialVersionUID, no-arg constructor, and explicit constructors.
The prior time I cleaned/cleared/refreshed my Tomcat cache and did whatever else to force it to reload. I believe when I added the Jackson dependencies, it fixed my compile time errors, but since tomcat missed them, at runtime Spring MVC did not discover the Jackson libraries, and produced the 406 error about unacceptable response type.

Also, make sure that you add two jackson related jar files.
jackson-core-asl-1.9.8.jar
jackson-mapper-asl-1.9.8.jar
The version can be different.

I know that this is an old thread, but maybe someone will encounter the same problem as me. I got that exception when migrating an application from Spring 4.0.3.RELEASE to Spring 4.1.0.RELEASE. In my case updating Jackson from 1.9.x to 2.4.x did the trick.

I have got same exception when migrating from spring 3.x to spring 4.x.
I solved it with updating jackson dependencies from
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
to
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.5.1</version>
</dependency>
Nothing else was needed for me.

Sending the Accept: application/xml header does not work. But sending Accept: application/json actually works, and jackson mapper kicks in. I got rid of my 406 and got my serialized java object in json format with no more config than #ResponseBody and return new MyObject()
:)
Thanks skaffman for this information, and thanks Bozho for the working header value :D

This question pops up everywhere on the net and I got bitten by it a couple of times. Spring 3.0.6 (and 5 possibly) has some issues in rendering json. Once I changed to 3.1.0.RELEASE version eveyrything worked AS IS. Without any config changes. Things to note is, the return method must have #ResponseBody (as in the example before) and must be in servlet-context.xml or your spring context configuration file.

May be my answer is a bit late, but it may help some one else visiting this question.
I got my problem resolved by adding
hibernate-validator-4.0.2
and gave me another exception (class not found exception: org.slf4j.LoggerFactory) which i resolved by adding
slf4j-api-1.5.6.jar
I hope it will help someone.

Related

Some characters (e.g. brackets) are coming encoded in Spring #RequestBody. How to decode them?

Let's consider this fragment of code:
#ResponseBody
#RequestMapping(value = "/getFiltered", method = RequestMethod.POST)
public ResponseEntity<OraPhysicalGoodMiniDataWrapper> getFilteredProducts(#RequestBody OraSalesOfGoodsFilters filters) {
return oraProductListController.getFilteredProducts(filters);
}
filters parameter has String named searchValue.
The problem is: when I pass for example searchValue: "(2016)" in json, Spring controller receives searchValue=(2016).
I tried to decode it with Java URLDecoder but it didn't work.
And my question is:
is there any Java method which could decode all such characters in String? Or should I write my own method?
This is your problem solution. using javascript or spring settings.
Javascript
var param = {
"searchValue": "(2016)"
};
$.ajax({
type: 'POST',
dataType: 'JSON',
data: JSON.stringify(param),
contentType:"application/json; charset=UTF-8",
url: '/test/filter',
error: function() {
// error
},
success: function(returnJSON) {
// success
}
}):
Spring settings
Pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.0.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.0.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.0.4</version>
</dependency>
servlet.xml
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
As Joop Eggen mentioned in comment - the StringEscapeUtils.unescapeXml(String value)method proved to be helpful.
It's kind of werid that it's unescapeXml(), not unescapeJavaScript() (which is not working), because I pass the value on frontend as JSON (not XML) from JavaScript, but I'm glad it works.

Spring Data REST(using Spring Boot) - Hibernate Validation Localization

I am currently evaluating Spring Data REST.
I started with this simple example: link
It works out of the box. But now, in the next step, I wanted to try some validation to see how the framework reacts. So I simply annotated the Personclass:
#Size(min = 2, message = "{test.error.message}")
private String firstName;
The validation itself is working, I get an error message. The message is resolved if I put a file called ValidationMessages.properties in the root of the classpath (see here why).
Now, instead of having the files in the root I wanted to place them in a subfolder (e.g. lang/ValidationMessages.properties) and use Spring MessageSource instead of the default approach.
After some research I found the following question:
MessageInterpolator in Spring
Unfortunately using the following bean definitions does not work:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>lang/ValidationMessages</value>
</list>
</property>
</bean>
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource" ref="messageSource"/>
</bean>
</beans>
The corresponding dependencies inside the pom.xml (just in case):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Does anyone know what I am missing? Could it be due to the fact that I am not using Spring MVC but Spring Data REST? If yes, is there a way of getting this to work?
After some additional investigation (and a lot of searching) I found a solution to the issue.
PROBLEM
Hibernate does not use beans for the validator factory, thats why the LocalValidatorFactoryBean is not used.
For more details look into org.hibernate.cfg.beanvalidation.TypeSafeActivator#activate(ActivationContext activationContext)
FIRST APPROACH
You can actually specify which factory to use by using this property: javax.persistence.validation.factory
Unfortunately this can't be used (yet) inside Spring Boot's application.properties.
(see this Issue on GitHub)
SOLUTION
Using the workaround described in the linked GitHub issue works.
You have to provide a configuration for Hibernate:
#Configuration
public class HibernateConfig extends HibernateJpaAutoConfiguration {
#Autowired
private ValidatorFactory validator;
#Override
protected void customizeVendorProperties(Map<String, Object> vendorProperties) {
super.customizeVendorProperties(vendorProperties);
vendorProperties.put("javax.persistence.validation.factory", validator);
}
}
Using this approach the messages get resolved correctly.
HibernateJpaAutoConfiguration can not work anymore (after sprint boot 2.10)
You can do like this if you are using Spring Boot 2.1.0+:
#Configuration
#Lazy
class SpringValidatorConfiguration {
#Bean
#Lazy
public HibernatePropertiesCustomizer hibernatePropertiesCustomizer(final Validator validator) {
return new HibernatePropertiesCustomizer() {
#Override
public void customize(Map<String, Object> hibernateProperties) {
hibernateProperties.put("javax.persistence.validation.factory", validator);
}
};
}
}
The idea from Spring Boot 2.0.0 M6 - Add Hibernate Interceptor
and Spring Boot - Hibernate custom constraint doesn't inject Service

com.sun.xml.messaging.saaj.soap.ver1_1.SOAPMessageFactory1_1Impl cannot be cast to javax.xml.soap.MessageFactory

I'm using WebLgic have the following saaj soap message factory. I've tried leaving off the messageFactory and just the soapVersion and vice Versa. I've also tried the different messageFactory Impl beans that are commented out. I'm still getting the error in the title. Why is t trying to use version 1.1?
<bean id="saajMessageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory">
<property name="messageFactory">
<bean class="com.sun.xml.messaging.saaj.soap.MessageFactoryImpl"
/>
<!-- <bean class="com.sun.xml.messaging.saaj.soap.ver1_2.SOAPMessageFactory1_2Impl"
/> -->
<!-- <bean class="weblogic.xml.saaj.MessageFactoryImpl"/> -->
</property>
<property name="soapVersion">
<util:constant static-field="org.springframework.ws.soap.SoapVersion.SOAP_12" />
</property>
</bean>
Error:
SAAJ MessageFactory: Unable to create message factory for SOAP: com.sun.xml.messaging.saaj.soap.ver1_1.SOAPMessageFactory1_1Impl cannot be cast to javax.xml.soap.MessageFactory; nested exception is javax.xml.soap.SOAPException: Unable to create message factory for SOAP: com.sun.xml.messaging.saaj.soap.ver1_1.SOAPMessageFactory1_1Impl cannot be cast to javax.xml.soap.MessageFactory
at org.springframework.ws.support.DefaultStrategiesHelper.instantiateBean(DefaultStrategiesHelper.java:188)
at org.springframework.ws.support.DefaultStrategiesHelper.getDefaultStrategies(DefaultStrategiesHelper.java:134)
at org.springframework.ws.support.DefaultStrategiesHelper.getDefaultStrategy(DefaultStrategiesHelper.java:219)
at org.springframework.ws.support.DefaultStrategiesHelper.getDefaultStrategy(DefaultStrategiesHelper.java:203)
at org.springframework.ws.client.core.WebServiceTemplate.initMessageFactory(WebServiceTemplate.java:310)
pom file:
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.messaging.saaj</groupId>
<artifactId>saaj-impl</artifactId>
<version>1.3.15</version>
</dependency>
<dependency>
<groupId>javax.xml.soap</groupId>
<artifactId>saaj-api</artifactId>
<version>1.3.5</version>
</dependency>
Weblogic.xml:
<prefer-application-packages>
<package-name>javax.xml.soap.*</package-name>
<package-name>javax.xml.ws.*</package-name>
<package-name>com.sun.xml.messsaging.saaj.*</package-name>
</prefer-application-packages>
I should also add that I tried setting various this JVM argument with various options: -Djavax.xml.soap.MessageFactory=weblogic.xml.saaj.MessageFactoryImpl
such as com.sun.xml.messaging.saaj.soap.ver1_2.SOAPMessageFactory1_2Impl. The error message now reflects the new Impl class, but I still can't get around the error.
I'm not sure exactly what ended up fixing this issue, but I was also getting some other errors as I tried different things, and I finally got everything working as specified in this post: java.lang.NoClassDefFoundError: org/apache/cxf/jaxrs/impl/UriBuilderImpl. I ended up removing those pom file entries above.
One thing I did have to do was to download a new version of Maven as the one that came in my VM was giving me problems.

Setting up spring app with spring data repositories and mongo db

I am facing an issue when defining mongo repository in application-context.xml
Following is the error i get in xml
Error occured processing XML tried to access method org.springframework.context.annotation.AnnotationConfigUtils.processCommonDefinitionAnnotations
(Lorg/springframework/beans/factory/annotation/AnnotatedBeanDefinition;)V from class org.springframework.data.repository.config.RepositoryComponentProvider'. See Error Log for more details servlet-context.xml /master/WebContent/WEB-INF/config line 24 Spring Beans Problem
I am attaching a screenshot of env for reference.
I am using eclipse Kepler version and pom properties File is like this
<java-version>1.7</java-version>
<org.springframework-version>4.0.1.RELEASE</org.springframework-version>
<org.jackson-version>2.3.0</org.jackson-version>
<spring-data-mongodb>1.4.0.RELEASE</spring-data-mongodb>
Spring data commons version is 1.7
spring data mongo db version 1.4.
I see the error in eclipse project when I open context xml.
Interestingly I have another project that works well.Only difference is that it doesn't have spring MVC and jackson binaries otherwise its similar project.
exception stack trace:
!ENTRY org.springframework.ide.eclipse.beans.core 1 0 2014-03-01
00:04:11.839 !MESSAGE Error occured processing
'/master/WebContent/WEB-INF/config/servlet-context.xml' !STACK 0
java.lang.IllegalAccessError: tried to access method
org.springframework.context.annotation.AnnotationConfigUtils.processCommonDefinitionAnnotations(Lorg/springframework/beans/factory/annotation/AnnotatedBeanDefinition;)V
from class
org.springframework.data.repository.config.RepositoryComponentProvider
at
org.springframework.data.repository.config.RepositoryComponentProvider.findCandidateComponents(RepositoryComponentProvider.java:121)
at
org.springframework.data.repository.config.RepositoryConfigurationSourceSupport.getCandidates(RepositoryConfigurationSourceSupport.java:69)
at
org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport.getRepositoryConfigurations(RepositoryConfigurationExtensionSupport.java:54)
at
org.springframework.data.repository.config.RepositoryConfigurationDelegate.registerRepositoriesIn(RepositoryConfigurationDelegate.java:88)
at
org.springframework.data.repository.config.RepositoryBeanDefinitionParser.parse(RepositoryBeanDefinitionParser.java:67)
at
org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:74)
at
org.springframework.ide.eclipse.beans.core.internal.model.namespaces.DelegatingNamespaceHandlerResolver$ElementTrackingNamespaceHandler.parse(DelegatingNamespaceHandlerResolver.java:177)
at
org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1427)
at
org.springframework.ide.eclipse.beans.core.internal.model.BeansConfig$ErrorSuppressingBeanDefinitionParserDelegate.parseCustomElement(BeansConfig.java:1400)
at
org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1417)
at
org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:187)
at
org.springframework.ide.eclipse.beans.core.internal.model.BeansConfig$ToolingFriendlyBeanDefinitionDocumentReader.doRegisterBeanDefinitions(BeansConfig.java:1330)
at
org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:110)
at
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:494)
at
org.springframework.ide.eclipse.beans.core.internal.model.BeansConfig$2.registerBeanDefinitions(BeansConfig.java:402)
at
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:391)
at
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:335)
at
org.springframework.ide.eclipse.beans.core.internal.model.BeansConfig$2.loadBeanDefinitions(BeansConfig.java:388)
at
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:303)
at
servlet context.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<context:component-scan base-package="com.xxxx.yyyyy" />
<!-- Mongo DB Configuration -->
<mongo:mongo id="mongo" host="monopolyvm3" port="27017" />
<mongo:db-factory dbname="test" mongo-ref="mongo" />
<mongo:db-factory id="mongoDbFactory" dbname="cloud" mongo-ref="mongo" />
<mongo:repositories base-package="com.xxxx.yyyyy" />
<bean id="mappingContext" class="org.springframework.data.mongodb.core.mapping.MongoMappingContext" />
<bean id="defaultMongoTypeMapper"
class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper">
<constructor-arg name="typeKey"><null/></constructor-arg>
</bean>
<bean id="mappingMongoConverter" class="org.springframework.data.mongodb.core.convert.MappingMongoConverter">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
<constructor-arg name="mappingContext" ref="mappingContext" />
<property name="typeMapper" ref="defaultMongoTypeMapper" />
</bean>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongoDbFactory" />
<constructor-arg name="mongoConverter" ref="mappingMongoConverter" />
<property name="writeConcern" value="SAFE" />
</bean>
</beans>
error is seen at the following line..
In my case it was spring data jpa version which was causing problem. I am not using spring data mongodb but spring data jpa instead. I started this projected today with latest versions (spring-framework 4.0.2.RELEASE, spring-data-jpa 1.5.0.RELEASE). I ensured that all transitive dependencies from maven (from spring side as well as from spring data side) are that of latest version but no lock.
Following this thread, tried to downgrade spring version to 4.0.0.RELEASE but no luck. I even explored the org.springframework.context.annotation.AnnotationConfigUtils class from spring-context-4.0.2.RELEASE.jar (and also in spring-context-4.0.0.RELEASE.jar) from within my workspace and confirmed that indeed processCommonDefinitionAnnotations is a public method thus IllegalAccessError can not be an issue resulting from these jars.
Finally I downgraded my spring-data-jpa from 1.5.0.RELEASE to 1.4.4.RELEASE and voila all problems are solved on maven update. I am using STS 3.4 if it helps anyone.
Since this was the first post I found on googling this error, thought of posting it here so that others who are facing same problems can potentially solve it with this tip. I have opened bug report at https://jira.springsource.org/browse/DATAJPA-490
#Oliver, tried the dependency management suggested but no luck. I have also added dependency:list output to the bug report as requested.
Finally I changed the spring jar version to 4.0.0 and then removed all spring jars from the maven repository and tried to (updated maven first)build again..It worked. I am pretty sure that it will work with 4.0.1 spring jars also.( I was having another project with the same configuration and it was working fine with 4.0.1 jars:)) I contribute this issue to maven and eclipse. Some issue that I don't have any clue at all.
Make sure you don't accidentally pull in an older Spring version (something before 3.2.5) into the classpath. The older methods don't have the method listed in the exception public. This is then causing the exception. I recommend to use the following Maven config snippet to enforce all Spring libraries to be in 4.0.2:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>4.0.2.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
I ran into the same issue. After spending several hours fighting with the problem #Avnish's answer pointed me in the right direction. More specifically, the issue he opened at https://jira.springsource.org/browse/DATAJPA-490 really cleared things up.
Spring-Data-JPA 1.5.1.BUILD-SNAPSHOT or 1.6.0.BUILD-SNAPSHOT has a guard that indicates exactly which jar is causing the problem.
In my case, I was using Eclipse Juno (4.2) with Spring IDE 3.4.0 which was causing the problem. I had to upgrade to Spring IDE 3.5.0 to make the issue go away. I had to use the http://dist.springsource.com/snapshot/TOOLS/nightly/e4.2 update site to update Juno to Spring IDE 3.5.0.
It also appears that STS 3.5.0RC1 and beyond get this working as well.
The real solution is to upgrade your eclipse/STS spring plugin to the latest.
This is mentioned in https://jira.springsource.org/browse/DATAJPA-490, but not that clearly.

Spring REST XML service not accepting XML as "accept" header

I have several REST services defined that are currently returning JSON formatted objects as service response bodies. I'm trying to make this service also accept XML as a new requirement though it does not accept this.
I'm following the spring-mvc-showcase sample project and have setup my pom.xml dependencies almost identically, my service definitions likewise are very simple.
#Controller
#RequestMapping(value = "api/sales/*")
public class SalesController {
#RequestMapping(value = "/countries", method = RequestMethod.GET)
#ResponseBody
public List<NamedEntity> getCountries() {
NamedEntity has the appropriate #XmlRootElement annotation.
Could somebody explain the most basic requirements that I would need to get XML as a ResponseBody that the spring-mvc-showcase sample project is using.
EDIT: Added spring MVC sample.
The sample from the spring-mvc-showcase is as follows:
package org.springframework.samples.mvc.messageconverters;
#Controller
#RequestMapping("messageconverters/*")
public class MessageConvertersController {
#RequestMapping(value="/xml", method=RequestMethod.GET)
public #ResponseBody JavaBean writeXml() {
return new JavaBean("bar", "fruit");
Check the request header, client needs to have "application/xml" in the header, rather than "application/json "
Having said this make sure you have registered appropriate message converter for your object. If you are using Java 6 then Spring will auto detect JAXB in your classpath or else you can manually add the converter.
Add #Produces("application/xml") to getCountries()
You need to send "application/xml", not "application/application+xml". Also consider using:
#RequestMapping(value = "/countries", method = RequestMethod.GET, produces={"application/json", "application/xml"})
This ensures your method responds to those media types only and rejects others with 406 HTTP status code.
try this dispatcher servlet config.
<mvc:annotation-driven
content-negotiation-manager="contentManager" />
<bean id="contentManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="false" />
<property name="ignoreAcceptHeader" value="false" />
<property name="defaultContentType" value="application/json" />
<property name="useJaf" value="false" />
</bean>
and some dependency
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.4.3</version>
</dependency>

Categories