我知道Spring MVC可以輕鬆地返回Json格式的模型;然而,我嘗試了不同的方法來以CSV格式(通過Jackson)返回模型,但無法成功。如何使Spring MVC返回CSV像返回JSON一樣方便
我該怎麼辦?
附上我的模型代碼,控制器代碼,並gradle.build如下:
非常感謝!
型號:
@JsonPropertyOrder({ "staffName", "name" })
public class Greeter
{
String name;
String staffName[];
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String[] getStaffName()
{
return staffName;
}
public void setStaffName(String[] staffName)
{
this.staffName = staffName;
}
}
控制器:
@Controller
public class GreetingController {
@RequestMapping(value = "/greeter/json", method = RequestMethod.GET)
public @ResponseBody
Greeter getGreeterInJSON() {
Greeter greeter = new Greeter();
greeter.setName("default");
greeter.setStaffName(new String[] { "ye", "lichi" });
return greeter;
}
@RequestMapping(value = "/greeter/csv", method = RequestMethod.GET, consumes = "text/csv")
public @ResponseBody
Greeter getGreeterInCSV(HttpServletResponse response) {
Greeter greeter = new Greeter();
greeter.setName("default");
greeter.setStaffName(new String[] { "ye", "lichi" });
CsvMapper mapper = new CsvMapper();
CsvSchema schema = mapper.schemaFor(Greeter.class);
ObjectWriter writer = mapper.writer(schema.withLineSeparator("\n"));
File greeterCSV = new File("greeterCSV.csv");
try {
writer.writeValue(greeterCSV, greeter);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return greeter;
}
}
的build.gradle依賴性:
dependencies {
compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
compile ('org.springframework:spring-context:4.0.0.RELEASE')
compile("org.springframework.boot:spring-boot-starter-web:0.5.0.M6")
compile("org.thymeleaf:thymeleaf-spring3:2.0.17")
// compile "org.codehaus.jackson:jackson-mapper-asl:1.9.13"
compile 'com.fasterxml.jackson.core:jackson-databind:2.3.0'
compile 'com.fasterxml.jackson.core:jackson-core:2.3.0'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.3.0'
compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-csv:2.3.0'
testCompile group: 'junit', name: 'junit', version: '4.+'
testCompile "org.mockito:mockito-all:1.9.5"
}
編輯:
Tomcat的錯誤:
HTTP狀態415 -
類型狀態報告
消息
描述,因爲請求的實體是不被請求的資源支持的格式,服務器拒絕了這個請求請求的方法。
以何種方式它不能正常工作?請提供任何堆棧跟蹤等。 –