001/*
002 * Copyright 2002-2017 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.lang.Nullable;
023import org.springframework.util.StringUtils;
024import org.springframework.web.util.WebUtils;
025
026/**
027 * {@link org.springframework.web.servlet.ThemeResolver} implementation that
028 * uses a theme attribute in the user's session in case of a custom setting,
029 * with a fallback to the default theme. This is most appropriate if the
030 * application needs user sessions anyway.
031 *
032 * <p>Custom controllers can override the user's theme by calling
033 * {@code setThemeName}, e.g. responding to a theme change request.
034 *
035 * @author Jean-Pierre Pawlak
036 * @author Juergen Hoeller
037 * @since 17.06.2003
038 * @see #setThemeName
039 */
040public class SessionThemeResolver extends AbstractThemeResolver {
041
042        /**
043         * Name of the session attribute that holds the theme name.
044         * Only used internally by this implementation.
045         * Use {@code RequestContext(Utils).getTheme()}
046         * to retrieve the current theme in controllers or views.
047         * @see org.springframework.web.servlet.support.RequestContext#getTheme
048         * @see org.springframework.web.servlet.support.RequestContextUtils#getTheme
049         */
050        public static final String THEME_SESSION_ATTRIBUTE_NAME = SessionThemeResolver.class.getName() + ".THEME";
051
052
053        @Override
054        public String resolveThemeName(HttpServletRequest request) {
055                String themeName = (String) WebUtils.getSessionAttribute(request, THEME_SESSION_ATTRIBUTE_NAME);
056                // A specific theme indicated, or do we need to fallback to the default?
057                return (themeName != null ? themeName : getDefaultThemeName());
058        }
059
060        @Override
061        public void setThemeName(
062                        HttpServletRequest request, @Nullable HttpServletResponse response, @Nullable String themeName) {
063
064                WebUtils.setSessionAttribute(request, THEME_SESSION_ATTRIBUTE_NAME,
065                                (StringUtils.hasText(themeName) ? themeName : null));
066        }
067
068}