![](/img/trans.png)
[英]406 Not Acceptacle error while hitting REST API from postman
[英]406 error while retrieving the details in REST and hibernate
我正在嘗試使用REST和休眠方式獲取XML國家/地區的詳細信息。 但是當點擊下面的URL是我得到的錯誤。 我已將請求中的標頭接受設置為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;
}
模型
@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();
}
服務
@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;
}
有人可以幫忙嗎..
在pom.xml
使用spring推薦的jackson-dataformat-xml
庫。 存在JAXB庫(在JDK> = 1.6中內置)后,即使沒有XML批注,它也會為您自動進行XML轉換。 但是,您可以使用@JacksonXml..
批注為xml提供所需的結構。
為了在這里達到預期的效果,我將創建一個包裝器類並更新控制器,如下所示:
//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());
}
注意:這里不需要XML Wrapper類。 Spring可以很好地使用<List><Items>
進行默認的數組轉換,但是建議按照所需的結構對XML進行調整。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.