【发布时间】:2017-01-19 08:19:48
【问题描述】:
我已经编写了一个简单的 Web 服务,我已经能够成功地从数据库值返回 json,此时我正试图从数据库中以 xml 形式返回数据库值,但得到 406 是不可接受的。这是我的诚实尝试:
控制器 sn-ps
@RestController
public class CountryController {
@Autowired
CountryService countryService;
@RequestMapping(value = "/getAllCountries", method = RequestMethod.GET, headers = "Accept=application/xml")
public List<Country> getCountries() {
List<Country> listOfCountries = countryService.getAllCountries();
return listOfCountries;
}
这是我的 pojo 类 sn-ps
@XmlRootElement(name="Country")
@Entity
@Table(name="COUNTRY")
public class Country{
@Id
@Column(name="id")
@GeneratedValue(strategy = GenerationType.AUTO)
int id;
@Column(name="countryName")
String countryName;
@Column(name="population")
long population;
public Country() {
super();
}
pom.xml 的 sn-p 显示我用于序列化以检索 xml 数据的依赖库
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.2.11</version>
</dependency>
已编辑以显示 XML 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<mvc:annotation-driven/>
<resources mapping="/resources/**" location="/resources/" />
在尝试以上使用休息客户端返回 406 不可接受。请协助。
【问题讨论】:
-
在 Mapping 注解后使用 @ResponseBody 注解
-
你也使用过
它支持将对象与 XML 文件相互转换
标签: java xml spring rest maven