spring - Angular 4 + Spring Boot + ContentNegotiatingViewResolver
问题描述
我有一个应用程序,我在其中使用 Angular 4 和 Spring Boot。它有主页、仪表板、检查、报告页面等...当我单击导航菜单中的任何链接时,它会转到该页面。当我点击 localhost:8080 时,它会转到主页。
早些时候,我们没有任何 View Resolver。我们需要通过单击超链接在报告页面之一中下载 Excel/PDF/CSV。所以我添加了一个配置类和控制器并进行了测试,当我点击直接 url 时它工作正常(意味着我可以下载 excel/pdf/csv)。但是当我点击 localhost:8080 时,它没有显示主页,而是下载了 Excel。我确定我缺少一些配置。请提供任何帮助...我可以在需要时分享更多代码...
直接网址:localhost:8080/api/inspDefectHistReportDownload.xls
WebConfiguration.java
@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer
.defaultContentType(MediaType.APPLICATION_JSON)
.favorPathExtension(true);
}
/*
* Configure ContentNegotiatingViewResolver
*/
@Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(manager);
// Define all possible view resolvers
List<ViewResolver> resolvers = new ArrayList<>();
//resolvers.add(csvViewResolver());
resolvers.add(excelViewResolver());
//resolvers.add(pdfViewResolver());
resolver.setViewResolvers(resolvers);
return resolver;
}
/*
* Configure View resolver to provide XLS output using Apache POI library to
* generate XLS output for an object content
*/
@Bean
public ViewResolver excelViewResolver() {
return new ExcelViewResolver();
}
/*
* Configure View resolver to provide Csv output using Super Csv library to
* generate Csv output for an object content
*/
@Bean
public ViewResolver csvViewResolver() {
return new CsvViewResolver();
}
/*
* Configure View resolver to provide Pdf output using iText library to
* generate pdf output for an object content
*/
@Bean
public ViewResolver pdfViewResolver() {
return new PdfViewResolver();
}
当然我有 ReportController、ExcelView... 和 ExcelViewResolver.java 等...(如果需要,我也可以发布这些类)
解决方案
经过长时间的调查,我发现下面的代码对我有用。现在我可以通过相应的 url 转到主页和其他屏幕,点击特定屏幕中的超链接,我可以下载所需的 excel。
WebConfiguration.java
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer
.defaultContentType(MediaType.APPLICATION_JSON)
.ignoreAcceptHeader(true);
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.enableContentNegotiation(
new ExcelView()
);
}
推荐阅读
- javascript - 为什么 String.raw 可以处理双反斜杠而常规转义却不能?
- c++ - 如何在级数求和中达到最大精度?
- javascript - javascript 不考虑上下文 JSON 数据
- python - 如何使用 tkinter GUI 可视化 matplotlib 预测?
- reactjs - 使 apollo 查询组件在 React 中可重用
- go - 具有空白名称的方法的目的是什么?
- image-processing - 使图像中的边缘变细
- python - 如何修复 Tweepy 错误“抱歉,该页面不存在。” 在建议用户()
- android - android设备上的错误分辨率以供查看
- python - 对 numpy 数组的选定行求和的简洁方法