Spring配置多个ViewResolver

阅读更多

项目中有时候需要同时使用Jsp页面和Html静态页面,也可能是xml或者json

spring可以配置多个ViewResolver来处理不同类型的页面

 

例子如下,首先构建一个自己的ViewResolver

这个ViewResolver用来匹配html静态页面

如果没有匹配成功,则checkResource返回false,由其他优先级更低的ViewResolver继续尝试匹配

 

import java.io.File;
import java.util.Locale;

import org.springframework.web.servlet.view.InternalResourceView;

public class HtmlResourceView extends InternalResourceView {

	@Override
	public boolean checkResource(Locale locale) {
		File file = new File(this.getServletContext().getRealPath("/") + getUrl());
		return file.exists();// 判断该页面是否存在
	}

}

 

 

Spring ApplicationContext

用addResourceHandlers把html静态页面的路径设为静态资源

然后配置两个ViewResolver

优先级较高的为刚才创建的htmlViewResolver将viewResolver.setOrder(0)

优先级较低的为映射jsp页面的jspViewResolver将viewResolver.setOrder(1)

 

@Configuration
@Profile(value = { "default" })
@EnableWebMvc
@ComponentScan(basePackages = "com.demo")
public class WebContext extends WebMvcConfigurerAdapter{
	
	@Override
       public void addResourceHandlers(ResourceHandlerRegistry registry) {
       registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
       registry.addResourceHandler("/html/**").addResourceLocations("/html/");
	}
	
	@Bean
	public ViewResolver htmlViewResolver(){
	InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
	viewResolver.setViewClass(HtmlResourceView.class);
	viewResolver.setPrefix("/html/");
	viewResolver.setSuffix(".html");
	viewResolver.setOrder(0);
	return viewResolver;
	}
	
	@Bean
	public ViewResolver jspViewResolver(){
	InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
	viewResolver.setViewClass(JstlView.class);
	viewResolver.setPrefix("/jsp/");
	viewResolver.setSuffix(".jsp");
	viewResolver.setOrder(1);
	return viewResolver;
	}

}

 

 

Controller

假设返回new ModelAndView("homePage")

按照前面配置的两个ViewResolver

Spring会先匹配 /html/homePage.html

如果不存在,再匹配 /jsp/homePage.jsp

 

@RequestMapping(value = { "/" , "" }, produces = "text/html; charset=utf-8")
public ModelAndView visitHomePage(HttpServletRequest request) {
	return new ModelAndView("homePage");
}

 

这样就可以在Spring中配置多个ViewResolver

按照优先级映射不同的页面文件

 

以上

 

你可能感兴趣的:(spring,ViewResolver,html,jsp)