【问题标题】:406 error while retrieving the details in REST and hibernate在 REST 和休眠中检索详细信息时出现 406 错误
【发布时间】:2018-07-03 06:51:02
【问题描述】:

我正在尝试使用 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.

控制器

@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();
}

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

有人可以帮忙吗..

【问题讨论】:

  • 您的依赖项中有Jackson 吗?
  • @Thomas 是的,我在依赖项中有杰克逊

标签: java xml spring hibernate rest


【解决方案1】:

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 将使用&lt;List&gt;&lt;Items&gt; 处理默认数组转换,但它建议根据所需的结构来塑造您的 XML。

【讨论】:

猜你喜欢
  • 2017-12-10
  • 1970-01-01
  • 2020-10-07
  • 1970-01-01
  • 2019-10-14
  • 2011-01-31
  • 1970-01-01
  • 2016-11-07
  • 2016-12-13
相关资源
最近更新 更多