001/* 002 * Copyright 2002-2013 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.web.servlet.theme; 018 019import javax.servlet.http.HttpServletRequest; 020import javax.servlet.http.HttpServletResponse; 021 022import org.springframework.util.StringUtils; 023import org.springframework.web.util.WebUtils; 024 025/** 026 * {@link org.springframework.web.servlet.ThemeResolver} implementation that 027 * uses a theme attribute in the user's session in case of a custom setting, 028 * with a fallback to the default theme. This is most appropriate if the 029 * application needs user sessions anyway. 030 * 031 * <p>Custom controllers can override the user's theme by calling 032 * {@code setThemeName}, e.g. responding to a theme change request. 033 * 034 * @author Jean-Pierre Pawlak 035 * @author Juergen Hoeller 036 * @since 17.06.2003 037 * @see #setThemeName 038 */ 039public class SessionThemeResolver extends AbstractThemeResolver { 040 041 /** 042 * Name of the session attribute that holds the theme name. 043 * Only used internally by this implementation. 044 * Use {@code RequestContext(Utils).getTheme()} 045 * to retrieve the current theme in controllers or views. 046 * @see org.springframework.web.servlet.support.RequestContext#getTheme 047 * @see org.springframework.web.servlet.support.RequestContextUtils#getTheme 048 */ 049 public static final String THEME_SESSION_ATTRIBUTE_NAME = SessionThemeResolver.class.getName() + ".THEME"; 050 051 052 @Override 053 public String resolveThemeName(HttpServletRequest request) { 054 String themeName = (String) WebUtils.getSessionAttribute(request, THEME_SESSION_ATTRIBUTE_NAME); 055 // A specific theme indicated, or do we need to fallback to the default? 056 return (themeName != null ? themeName : getDefaultThemeName()); 057 } 058 059 @Override 060 public void setThemeName(HttpServletRequest request, HttpServletResponse response, String themeName) { 061 WebUtils.setSessionAttribute(request, THEME_SESSION_ATTRIBUTE_NAME, 062 (StringUtils.hasText(themeName) ? themeName : null)); 063 } 064 065}