1 16 17 package org.springframework.web.servlet.support; 18 19 import java.util.Locale ; 20 21 import javax.servlet.ServletContext ; 22 import javax.servlet.ServletRequest ; 23 import javax.servlet.http.HttpServletRequest ; 24 25 import org.springframework.ui.context.Theme; 26 import org.springframework.ui.context.ThemeSource; 27 import org.springframework.web.context.WebApplicationContext; 28 import org.springframework.web.context.support.WebApplicationContextUtils; 29 import org.springframework.web.servlet.DispatcherServlet; 30 import org.springframework.web.servlet.LocaleResolver; 31 import org.springframework.web.servlet.ThemeResolver; 32 33 45 public abstract class RequestContextUtils { 46 47 54 public static WebApplicationContext getWebApplicationContext(ServletRequest request) 55 throws IllegalStateException { 56 57 return getWebApplicationContext(request, null); 58 } 59 60 73 public static WebApplicationContext getWebApplicationContext( 74 ServletRequest request, ServletContext servletContext) throws IllegalStateException { 75 76 WebApplicationContext webApplicationContext = (WebApplicationContext) request.getAttribute( 77 DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE); 78 if (webApplicationContext == null) { 79 if (servletContext == null) { 80 throw new IllegalStateException ("No WebApplicationContext found: not in a DispatcherServlet request?"); 81 } 82 webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext); 83 if (webApplicationContext == null) { 84 throw new IllegalStateException ("No WebApplicationContext found: no ContextLoaderListener registered?"); 85 } 86 } 87 return webApplicationContext; 88 } 89 90 96 public static LocaleResolver getLocaleResolver(HttpServletRequest request) { 97 return (LocaleResolver) request.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE); 98 } 99 100 110 public static Locale getLocale(HttpServletRequest request) { 111 LocaleResolver localeResolver = getLocaleResolver(request); 112 if (localeResolver != null) { 113 return localeResolver.resolveLocale(request); 114 } 115 else { 116 return request.getLocale(); 117 } 118 } 119 120 126 public static ThemeResolver getThemeResolver(HttpServletRequest request) { 127 return (ThemeResolver) request.getAttribute(DispatcherServlet.THEME_RESOLVER_ATTRIBUTE); 128 } 129 130 136 public static ThemeSource getThemeSource(HttpServletRequest request) { 137 return (ThemeSource) request.getAttribute(DispatcherServlet.THEME_SOURCE_ATTRIBUTE); 138 } 139 140 147 public static Theme getTheme(HttpServletRequest request) { 148 ThemeResolver themeResolver = getThemeResolver(request); 149 ThemeSource themeSource = getThemeSource(request); 150 if (themeResolver != null && themeSource != null) { 151 String themeName = themeResolver.resolveThemeName(request); 152 return themeSource.getTheme(themeName); 153 } 154 else { 155 return null; 156 } 157 } 158 159 } 160 | Popular Tags |