![](/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.