简体   繁体   中英

406 error while retrieving the details in REST and hibernate

I am trying to fetch the details of countries in XML using REST and hibernate. But when hitting the URL below is the error I get. I have set the header accepts in the request correctly to xml.

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

CONTROLLER

@RequestMapping(value = "/getAllCountries", method = 
RequestMethod.GET,produces="application/xml",
    headers = "Accept=application/xml")
public List<Country> getCountries() throws CustomerNotFoundException{

List<Country> listOfCountries = countryService.getAllCountries();
return listOfCountries;
}

MODEL

@XmlRootElement (name = "COUNTRY")
@XmlAccessorType(XmlAccessType.FIELD)
@Entity
@Table(name="COUNTRY")
public class Country{

@XmlAttribute
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
int id;

@XmlElement
@Column(name="countryName")
String countryName; 

@XmlElement
@Column(name="population")
long population;

public Country() {
super();
}

SERVICE

@Transactional
public List<Country> getAllCountries() {
    return countryDao.getAllCountries();
}

DAO

public List<Country> getAllCountries() {
    Session session = this.sessionFactory.getCurrentSession();
    List<Country> countryList = session.createQuery("from Country").list();
    return countryList;
}

Can someone please help..

Use spring recommended jackson-dataformat-xml library in pom.xml . It will do automatic XML transformation for you as soon as JAXB library (which is inbuilt in JDK >= 1.6) is present, even without XML annotations. However, you can use @JacksonXml.. annotations to given desired structure to your xml.

To achieve the desired result here, I will create a wrapper class and update my controller as below:

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

//wrapper class
@JacksonXmlRootElement(localName = "countries")
@Data //lombok
@AllArgsConstructor //lombok
public class Countries {

    @JacksonXmlElementWrapper(useWrapping = false)
    @JacksonXmlProperty(localName = "country")
    private List<Country> countries;

}

//controller
@RequestMapping(value = "/getAllCountries", method = RequestMethod.GET)
public Object getCountries() throws CustomerNotFoundException{
 return new Countries(countryService.getAllCountries());
}

NOTE: XML Wrapper class is not required here. Spring will just do fine with the default array transformation using <List><Items> , but its recommended to shape your XML as per desired structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM