2015-09-18 2 views
4

Я сделал простой веб-сервис для отдыха с Spring Boot 1.2.5, и он отлично работает для json, но я не могу заставить эту работу возвращать xml.Spring Boot REST с поддержкой XML

Это мой контроллер:

@RestController 
.. 
@RequestMapping(method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) 
@ResponseStatus(HttpStatus.OK) 
public List<Activity> getAllActivities() { 
    return activityRepository.findAllActivities(); 
} 

Когда я называю его с Accept: применение/JSON все работает, но когда я пытаюсь с применением/XML я получить HTML с 406 ошибкой и сообщение:

The resource identified by this request is only capable of generating responses 
with characteristics not acceptable according to the request "accept" headers. 

Мои объекты модели:

@XmlRootElement 
public class Activity { 

    private Long id; 
    private String description; 
    private int duration; 
    private User user; 
    //getters & setters... 
} 

@XmlRootElement 
public class User { 

    private String name; 
    private String id; 
    //getters&setters... 
} 


Мой pom.xml

<parent> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-parent</artifactId> 
    <version>1.2.5.RELEASE</version> 
    <relativePath /> <!-- lookup parent from repository --> 
</parent> 

<properties> 
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
    <java.version>1.8</java.version> 
</properties> 

<dependencies> 
    <dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-web</artifactId> 
    </dependency> 

    <dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-tomcat</artifactId> 
     <scope>provided</scope> 
    </dependency> 
    <dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-test</artifactId> 
     <scope>test</scope> 
    </dependency> 

</dependencies> 

<build> 
    <plugins> 
     <plugin> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-maven-plugin</artifactId> 
     </plugin> 
    </plugins> 
</build> 

мне нужны какие-то дополнительные банки в моей pom.xml, чтобы сделать эту работу делать? Я попытался добавить jaxb-api или jax-impl, но он не помог.

+0

Вы уверены, что вы устанавливаете его в 'приложения/xml' и не что-то другое? Включите ведение журнала отладки и посмотрите, что происходит внутри. –

+0

Можете ли вы поделиться своим POM-файлом !!! – Avis

+0

@Avis i paste my pom.xml – jgr

ответ

12

Чтобы сделать эту работу в Spring ботинке без использования Джерси нам нужно добавить эту зависимость:

<dependency> 
     <groupId>com.fasterxml.jackson.dataformat</groupId> 
     <artifactId>jackson-dataformat-xml</artifactId> 
</dependency> 

Выход быть немного уродливым, но он работает:

<ArrayList 
    xmlns=""> 
    <item> 
     <id/> 
     <description>Swimming</description> 
     <duration>55</duration> 
     <user/> 
    </item> 
    <item> 
     <id/> 
     <description>Cycling</description> 
     <duration>120</duration> 
     <user/> 
    </item> 
</ArrayList> 

Вот хороший учебник: http://www.javacodegeeks.com/2015/04/jax-rs-2-x-vs-spring-mvc-returning-an-xml-representation-of-a-list-of-objects.html

-1

Pls попробовать это

public @ResponseBody getAllActivities() { 

вместо

public List<Activity> getAllActivities() { 
+0

Я использую аннотацию RestController, поэтому мне не нужен ResponseBody, я редактировал мой вопрос. И мой json работает отлично, только xml doesnt. – jgr

-1

Мы можем добиться этого, как показано ниже:

Код


 package com.subu; 

     import java.io.Serializable; 

     import javax.persistence.Entity; 
     import javax.persistence.GeneratedValue; 
     import javax.persistence.Id; 
     import javax.persistence.Table; 
     import javax.xml.bind.annotation.*; 

     @Entity 
     @XmlRootElement(name = "person") 
     @Table(name="person") 

     public class Person implements Serializable{ 
      private static final long serialVersionUID = 1L; 

      @Id 
      @GeneratedValue 
      private Long id; 

      @XmlAttribute(name = "first-name") 
      private String first_name; 

      public Long getId() { 
       return id; 
      } 

      public void setId(Long id) { 
       this.id = id; 
      } 

      public String getFirst_name() { 
       return first_name; 
      } 

      public void setFirst_name(String first_name) { 
       this.first_name = first_name; 
      } 

      public String getLast_name() { 
       return last_name; 
      } 

      public void setLast_name(String last_name) { 
       this.last_name = last_name; 
      } 

      public String getDate_of_birth() { 
       return date_of_birth; 
      } 

      public void setDate_of_birth(String date_of_birth) { 
       this.date_of_birth = date_of_birth; 
      } 

      @XmlAttribute(name = "last-name") 
      private String last_name; 

      @XmlAttribute(name = "dob") 
      private String date_of_birth; 


     } 

 @RestController 
     public class PersonController { 

      @Autowired 
      private PersonRepository personRepository; 

      @RequestMapping(value = "/persons/{id}", method = RequestMethod.GET,produces={MediaType.APPLICATION_XML_VALUE},headers = "Accept=application/xml") 
      public ResponseEntity<?> getPersonDetails(@PathVariable Long id, final HttpServletRequest request)throws Exception { 
       Person personResponse=personRepository.findPersonById(id); 
       return ResponseEntity.ok(personResponse); 
      } 

     } 

 package com.subu; 

     import org.springframework.boot.SpringApplication; 
     import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 
     import org.springframework.boot.autoconfigure.SpringBootApplication; 
     import org.springframework.boot.builder.SpringApplicationBuilder; 
     import org.springframework.boot.context.web.SpringBootServletInitializer; 
     import org.springframework.context.annotation.ComponentScan; 
     import org.springframework.context.annotation.Configuration; 
     import org.springframework.scheduling.annotation.EnableScheduling; 


     @SpringBootApplication 
     @Configuration 
     @ComponentScan 
     @EnableAutoConfiguration 
     @EnableScheduling 
     public class Application extends SpringBootServletInitializer{ 



      public static void main(String[] args) { 
       SpringApplication.run(Application.class, args); 
      } 

      @Override 
      protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 
       return application.sources(Application.class); 
      } 

      private static Class<Application> applicationClass = Application.class; 

     } 

ScreenShot

+1

вы знаете, что это тема Java, когда ответ - сотни строк кода + конфигурация – EralpB

Смежные вопросы