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.ServletException; 020import javax.servlet.http.HttpServletRequest; 021import javax.servlet.http.HttpServletResponse; 022 023import org.springframework.web.servlet.ThemeResolver; 024import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 025import org.springframework.web.servlet.support.RequestContextUtils; 026 027/** 028 * Interceptor that allows for changing the current theme on every request, 029 * via a configurable request parameter (default parameter name: "theme"). 030 * 031 * @author Juergen Hoeller 032 * @since 20.06.2003 033 * @see org.springframework.web.servlet.ThemeResolver 034 */ 035public class ThemeChangeInterceptor extends HandlerInterceptorAdapter { 036 037 /** 038 * Default name of the theme specification parameter: "theme". 039 */ 040 public static final String DEFAULT_PARAM_NAME = "theme"; 041 042 private String paramName = DEFAULT_PARAM_NAME; 043 044 045 /** 046 * Set the name of the parameter that contains a theme specification 047 * in a theme change request. Default is "theme". 048 */ 049 public void setParamName(String paramName) { 050 this.paramName = paramName; 051 } 052 053 /** 054 * Return the name of the parameter that contains a theme specification 055 * in a theme change request. 056 */ 057 public String getParamName() { 058 return this.paramName; 059 } 060 061 062 @Override 063 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 064 throws ServletException { 065 066 String newTheme = request.getParameter(this.paramName); 067 if (newTheme != null) { 068 ThemeResolver themeResolver = RequestContextUtils.getThemeResolver(request); 069 if (themeResolver == null) { 070 throw new IllegalStateException("No ThemeResolver found: not in a DispatcherServlet request?"); 071 } 072 themeResolver.setThemeName(request, response, newTheme); 073 } 074 // Proceed in any case. 075 return true; 076 } 077 078}