1. 程式人生 > >springMVC原始碼分析--動態樣式ThemeResolver(一)

springMVC原始碼分析--動態樣式ThemeResolver(一)

Spring MVC中通過ThemeSource介面來提供對動態更換樣式的支援,並提供了ResourceBundleThemeSource這個具體實現類來提供通
過properties配置檔案對theme中的樣式的配置 
例如配置檔案中 內容為 helloworld=theme/default/css/helloworld.css 
而jsp檔案中使用 <link rel="stylesheet" type="text/css" href="<spring:theme code='helloworld'/>" /> 
來引用對helloworld這個樣式檔案的引入。由此來實現樣式檔案的動態引用,從而使spring mvc中可以實現換膚功能。 
如果說ThemeSource介面是提供瞭如何去取當前的theme的code與實際內容的mapping關係,那麼spring mvc提供的另外一個interfaceThemeResolver則是提供瞭如何去設定當前使用的theme的手段。 
  Spring MVC提供了三個ThemeReslover的實現類,分別是 :


(1)FixedThemeResolver:固定格式的theme,不能在系統執行時動態更改theme. 
(2)SessionThemeResolver:theme name存放在session中key值為 org.springframework.web.servlet.theme.SessionThemeResolver.THEME 的session attribute中。可在執行中通過更改session中的相應的key值來動態調整theme的值。

(3) CookieThemeResolver:theme name存放在cookie中key值為 org.springframework.web.servlet.theme.CookieThemeResolver.THEME 中。可在執行中通過更改cookie中的相應的key值來動態調整theme的值。 
以上Themesource和ThemeResolver在servlet context xml中的配置示例如下 :

<!-- 樣式-->
	<bean class="org.springframework.ui.context.support.ResourceBundleThemeSource"  id="themeSource">  
    	<property name="basenamePrefix" value="theme."></property>  
	</bean>  
  	<bean id="themeResolver"  class="org.springframework.web.servlet.theme.SessionThemeResolver">  
  		<property name="defaultThemeName" value="red" />  
	</bean>
然後在classpath路徑下建立樣式檔案:

我們預設使用的是red.properties中的內容,內容為多樣式檔案路徑:

helloworld=theme/red/css/helloworld.css

這樣我們需要建立css檔案了:

建立theme.jsp,裡面內容如下:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<link rel="stylesheet" type="text/css"
	href="<spring:theme code='helloworld'/>" />
</head>
<body>
	<div id="divTheme"><h1><spring:message code='hello'/></h1></div>
	<a href="changeTheme.action?themeName=blue"> blue</a>
	<a href="changeTheme.action?themeName=gray"> gray</a>
	<a href="changeTheme.action?themeName=red"> red</a>
</body>
</html>
Controlelr中的操作就是如下了:
@Controller
public class ThemeChange {
	private final Log logger = LogFactory.getLog(getClass());
	
	@Autowired
	private ThemeResolver themeResolver;

	@RequestMapping("/changeTheme")
	public String changeTheme(HttpServletRequest request,
			HttpServletResponse response, String themeName) {
		if(themeName == null){
			themeName = "red";
		}
		logger.info("current theme is " + themeResolver.resolveThemeName(request));
		themeResolver.setThemeName(request, response, themeName);
		logger.info("current theme change to " + themeResolver.resolveThemeName(request));
		return "theme";
	}
}
結果頁面如下:

(1)紅色樣式

(2)藍色樣式