适用于HTML和JSP的Viewresolver

时间:2018-06-18 10:04:58

标签: java spring-mvc

我正在构建一个示例应用程序,其中页面主要是HTML和JSP,所有配置都在java 中。当我尝试为HTML页面添加另一个viewresolver时,View解析器适用于jsp,它仍然重定向到JSP viewresolver。 也许是因为internalviewresolver是最后一个运行的原因,如果它找到任何东西它返回null并且api给出了404

以下是viewresolver的javaconfig:

public class ApplicationConfig 
{

@Bean
public ViewResolver jspViewResolver() {
    UrlBasedViewResolver resolver = new ChainableUrlBasedViewResolver();
    resolver.setPrefix("/resources/HTML/");
    resolver.setSuffix(".html");
    resolver.setOrder(0);
    return resolver;
}

public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/HTML/**").addResourceLocations("/HTML/");
}

@Bean
public ViewResolver getViewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".jsp");
    resolver.setOrder(1);
    return resolver;
}
}

ChainableUrlBasedViewResolver类:

public class ChainableUrlBasedViewResolver extends UrlBasedViewResolver {
public ChainableUrlBasedViewResolver() {
    setViewClass(InternalResourceView.class);
}

@Override
protected AbstractUrlBasedView buildView(String viewName) throws Exception {
    String url = getPrefix() + viewName + getSuffix();
    InputStream stream = getServletContext().getResourceAsStream(url);
    if (stream == null) {
        return new NonExistentView();
    }
    return super.buildView(viewName);
}

private static class NonExistentView extends AbstractUrlBasedView {
    @Override
    protected boolean isUrlRequired() {
        return false;
    }

    @Override
    public boolean checkResource(Locale locale) throws Exception {
        return false;
    }

    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        // Purposely empty, it should never get called
    }
  }
}

很多论坛都提到我们需要将html视为静态资源,但无法在javaconfig中执行此操作

PS:我从一些网站上复制了这段代码,提到这是唯一的方法

0 个答案:

没有答案