首页 > 解决方案 > 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 等...(如果需要,我也可以发布这些类)

标签: springspring-boot

解决方案


经过长时间的调查,我发现下面的代码对我有用。现在我可以通过相应的 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()
    );
}

推荐阅读