歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

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
按照優先級映射不同的頁面文件
以上

Struts2整合Spring方法及原理 http://www.linuxidc.com/Linux/2013-12/93692.htm

基於 Spring 設計並實現 RESTful Web Services http://www.linuxidc.com/Linux/2013-10/91974.htm

Spring-3.2.4 + Quartz-2.2.0集成實例 http://www.linuxidc.com/Linux/2013-10/91524.htm

使用 Spring 進行單元測試 http://www.linuxidc.com/Linux/2013-09/89913.htm

運用Spring注解實現Netty服務器端UDP應用程序 http://www.linuxidc.com/Linux/2013-09/89780.htm

Spring 3.x 企業應用開發實戰 PDF完整高清掃描版+源代碼 http://www.linuxidc.com/Linux/2013-10/91357.htm

Spring 的詳細介紹:請點這裡
Spring 的下載地址:請點這裡 

Copyright © Linux教程網 All Rights Reserved