1 24 package org.riotfamily.common.web.view; 25 26 import java.util.ArrayList ; 27 import java.util.Collections ; 28 import java.util.Iterator ; 29 import java.util.Locale ; 30 import java.util.Map ; 31 32 import javax.servlet.http.HttpServletRequest ; 33 34 import org.springframework.beans.factory.BeanFactoryUtils; 35 import org.springframework.beans.factory.ListableBeanFactory; 36 import org.springframework.beans.factory.NoSuchBeanDefinitionException; 37 import org.springframework.core.OrderComparator; 38 import org.springframework.web.servlet.DispatcherServlet; 39 import org.springframework.web.servlet.ModelAndView; 40 import org.springframework.web.servlet.RequestToViewNameTranslator; 41 import org.springframework.web.servlet.View; 42 import org.springframework.web.servlet.ViewResolver; 43 import org.springframework.web.servlet.support.RequestContextUtils; 44 import org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator; 45 46 49 public class ViewResolverHelper { 50 51 private ArrayList viewResolvers; 52 53 private RequestToViewNameTranslator viewNameTranslator; 54 55 public ViewResolverHelper(ListableBeanFactory beanFactory) { 56 Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors( 57 beanFactory, ViewResolver.class, true, false); 58 59 if (!matchingBeans.isEmpty()) { 60 this.viewResolvers = new ArrayList (matchingBeans.values()); 61 Collections.sort(this.viewResolvers, new OrderComparator()); 62 } 63 64 try { 65 this.viewNameTranslator = (RequestToViewNameTranslator) beanFactory.getBean( 66 DispatcherServlet.REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME, 67 RequestToViewNameTranslator.class); 68 } 69 catch (NoSuchBeanDefinitionException ex) { 70 this.viewNameTranslator = new DefaultRequestToViewNameTranslator(); 71 } 72 } 73 74 public View resolveView(HttpServletRequest request, ModelAndView mv) 75 throws ViewResolutionException { 76 77 if (mv.hasView() && !mv.isReference()) { 78 return mv.getView(); 79 } 80 return resolveView(request, mv.getViewName()); 81 } 82 83 public View resolveView(HttpServletRequest request, String viewName) 84 throws ViewResolutionException { 85 86 try { 87 if (viewName == null) { 88 viewName = viewNameTranslator.getViewName(request); 89 } 90 Iterator i = viewResolvers.iterator(); 91 while (i.hasNext()) { 92 ViewResolver viewResolver = (ViewResolver) i.next(); 93 Locale locale = RequestContextUtils.getLocale(request); 94 View view = viewResolver.resolveViewName(viewName, locale); 95 if (view != null) { 96 return view; 97 } 98 } 99 } 100 catch (Exception e) { 101 throw new ViewResolutionException(viewName, e); 102 } 103 throw new ViewResolutionException(viewName); 104 } 105 106 } 107 | Popular Tags |