我有一个应用程序,它总是从 spring 控制器返回 jsp 文件作为视图。如下图所示:
@RequestMapping("/home")
public class HomeController {
@RequestMapping(value = "", method = RequestMethod.GET)
public ModelAndView home(HttpServletResponse response){
ModelAndView modelView = new ModelAndView("home")
return modelView;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/content/**").addResourceLocations("WEB-INF/content/");
}
@Bean
public InternalResourceViewResolver setupViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
但现在代替 home.jsp 我必须为这个特定的映射返回 index.html。html 文件位于不同的文件夹中,不在 /WEB-INF/views/ 中,而是在 user/src 中。
我试过使用这样的东西,设置视图解析器的顺序,我在互联网上的某个地方看到了这段代码,它检查文件是否存在于路径中。但这对我不起作用。
它总是试图在 WEB-INF/views/ 中找到索引并且失败了。
@Bean
public ViewResolver htmlViewResolver() {
UrlBasedViewResolver resolver = new ChainableUrlBasedViewResolver();
resolver.setPrefix("/client/src/");
resolver.setSuffix(".html");
resolver.setOrder(0);
return resolver;
}
@Bean
public InternalResourceViewResolver setupViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setOrder(1);
return viewResolver;
}
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
}
}
}
任何想法如何使用 Spring 来做到这一点。