Spring REST 3 for XML and JSON Support

If we develop REST using Spring MVC, it will support XML and JSON data. I wrote a ContentNegotiationViewResorver in my Spring config beanapp-servlet.xml

<bean
        class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"
        p:order="1">
        <property name="mediaTypes">
            <map>
                <entry key="xml" value="application/xml" />
                <entry key="json" value="application/json" />
            </map>
        </property>
        <property name="defaultViews">
            <list>
                <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
                    <property name="marshaller">
                        <bean class="org.springframework.oxm.xstream.XStreamMarshaller"
                            p:autodetectAnnotations="true" />
                    </property>
                </bean>
                <bean
                    class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
            </list>
        </property>
    </bean>

And my Spring REST controller:

@Controller
@RequestMapping("/rest/customers")
class CustomerRestController {

protected Log log = LogFactory.getLog(CustomerRestController.class);

@RequestMapping(method = POST)
@ResponseStatus(CREATED)
public void createCustomer(@RequestBody Customer customer,
        HttpServletResponse response) {

    log.info(">>>" + customer.getName());
    response.setHeader("Location", String.format("/rest/customers/%s",
            customer.getNumber()));
}


@RequestMapping(value = "/{id}", method = GET)
@ResponseBody
public Customer showCustomer(@PathVariable String id) {
    Customer c = new Customer("0001", "teddy", "bean");
    return c;
}


@RequestMapping(value = "/{id}", method = PUT)
@ResponseStatus(OK)
public void updateCustomer(@RequestBody Customer customer) {
    log.info("customer: " + customer.getName());
}

I set the annotation @XStreamAlias("customer")in my client domain class. But when I try to access http://localhost:8080/rest/customers/teddy.xml, it always responds to JSON data.

I set the annotation @XmlRootElement(name="customer")in my client domain class. But when I try to access http://localhost:8080/rest/customers/teddy.json, it always responds to XML data.

Is there something wrong?

+5
source share
6 answers

, "xml" "text/xml", "application/xml". , , "favorPathExtension" "ContentNegotiationViewResolver" true ( !)

EDIT: GIT location - git://github.com/bijukunjummen/mvc-samples.git, , mvn tomcat: run, json http://localhost:8080/mvc-samples/rest/customers/teddy.json xml http://localhost:8080/mvc-samples/rest/customers/teddy.xml, JAXB2, XStream, JAXB. , , , JAXB Customer, Spring JSON, XML, ( , XMLRootElement Customer), , XML, . , , - XStream.

2: ! , xml, , json . , AnnotationMethodHandlerAdapter @ResponseBody , ViewResolvers MessageConverters, ContentNegotiatingViewResolver, @ModelAttribute , @ResponseBody, Resolvers. git@github.com:bijukunjummen/mvc-samples.git , . Spring, Spring , .

+2

? , , , .

+2

. , Spring 3, <mvc:annotation-driven/>. , , , , mvc.

oxm :

@XmlRootElement(name="person")
class Person {
   private String firstName;
   private String lastName;
}

@Controller 
@RequestMapping("person")
class PersonController {
   @RequestMapping("list")
   public @ResponseBody Person getPerson() {
      Person p = new Person();
      p.setFirstName("hello");
      p.setLastName("world");
      return p;
   }
}

(mvc ):

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:oxm="http://www.springframework.org/schema/oxm"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

        <oxm:jaxb2-marshaller id="jaxbMarshaller">
        <oxm:class-to-be-bound name="package.Person" />
    </oxm:jaxb2-marshaller>

    <bean
        class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="defaultContentType" value="text/html" />
        <property name="ignoreAcceptHeader" value="true" />
        <property name="favorPathExtension" value="true" />
        <property name="mediaTypes">
            <map>
                <entry key="json" value="application/json" />
                <entry key="xml" value="application/xml" />
            </map>
        </property>
        <property name="defaultViews">
            <list>
                <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
                <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
                    <property name="marshaller" ref="jaxbMarshaller" />
                </bean>
            </list>
        </property>
    </bean>
</beans>

JAXB, jaxb-api jaxb-impl .

, , app-servlet.xml. web.xml config null :

<listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/mvc-context.xml, /WEB-INF/spring/content-negotiation-context.xml</param-value>
    </context-param>
    <servlet>
        <servlet-name>app</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value/>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>app</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
+1

, , , :

@RequestMapping(value = "/{id}", method = GET)
@ResponseBody
public Customer showCustomer(@PathVariable String id) {
    Customer c = new Customer("0001", "teddy", "bean");
    return c;
}

MVC spring, , @ResponseBody, String , XML ContentNegotiatingViewResolver, ResponseBody, contentnegociationviewresolver , , , :

@RequestMapping(value = "/{id}", method = GET)

public String showCustomer(@PathVariable String id, ModelMap model) {
     Customer c = new Customer("0001", "teddy", "bean");
     model.addAttribute("customer",c);
    return "myView";
}

, , , app-servlet.xml

this bean, , .

<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/views/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

mkyong.com

+1
+1

browswer Accept Accept. , - (application/xml) , application/xml Accept.

I can recommend using RestClient http://code.google.com/p/rest-client/ to have full control over the Accept header (if at all) that you want to send.

I do not recommend using text / xml, since the default character set is US-ASCII, not UTF-8. This may cause problems with confusing coding in the future. You can always specify the encoding, but appliation / xml has UTF-8 encoding by default.

0
source

All Articles