Spring 4 官方文档学习(十一)Web MVC 框架之themes

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-themeresolver

做了一个小demo,放到了码云上,点我

 

1、概览

你可以应用Spring Web MVC框架themes来为你的应用设置全局的外观。

一个theme就是静态资源的一个集合 -- 通常是css和图片,会影响应用的视觉样式。

 

2、定义themes

想在你的web应用中使用这些themes,你必须设置 org.springframework.ui.context.ThemeSource 的一个实现。WebApplicationContext接口扩展了ThemeSource,但委托它的责任到指定的实现。 默认,该委托会是一个 org.springframework.ui.context.support.ResourceBundleThemeSource 实现,该实现从classpath的根路径加载properties文件。 想要使用一个自定义的ThemeSource实现或者想要配置ResourceBundleThemeSource的base name prefix,你可以住一个bean -- 使用保留名themeSource。web应用context会自动探测并使用它。

 

当使用ResourceBundleThemeSource时,theme是被定义在一个简单的properties文件中。该properties文件列出了组成该theme的资源。例如:

styleSheet=/themes/cool/style.css
background=/themes/cool/img/coolBg.jpg

properties的keys是view code 中指向主题元素的名字。对一个JSP来说,你可以使用 “spring:theme”自定义标签来完成 -- 非常类似于”spring:message”标签。 下面的JSP片段使用了前面定义的theme:

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
    <head>
        <link rel="stylesheet" href="<spring:theme code='styleSheet'/>" type="text/css"/>
    </head>
    <body style="background=<spring:theme code='background'/>">
        ...
    </body>
</html>

默认情况下,ResourceBundleThemeSource使用一个空的base name前缀。 结果就是,会从classpath的根路径来加载properties文件。所以,你可以将”cool.properties”主题定义文件放在classpath的根路径下,例如,在”/WEB-INF/classes”中。 ResourceBundleThemeSource会使用标准的Java resource bundle加载机制,允许主题的国际化。 例如,”/WEB-INF/classes/cool_nl.properties”,会引用Dutch文字。

 

3、theme resolvers

当你定义了themes,你需要决定使用哪个theme。DispatcherServlet 会查找bean themeResolver以找出使用哪个ThemeResolver实现。 theme resolver的工作方式非常类似于LocaleResolver。 它会探测用于某个request的theme,也可以更改该request的theme。 下面是Spring提供的theme resolvers :

 

Table 22.5. ThemeResolver implementations

ClassDescription

FixedThemeResolver

Selects a fixed theme, set using the defaultThemeName property.

SessionThemeResolver

The theme is maintained in the user’s HTTP session. It only needs to be set once for each session, but is not persisted between sessions.

CookieThemeResolver

The selected theme is stored in a cookie on the client.

Spring还提供了一个 ThemeChangeInterceptor,允许request使用一个简单的parameter来改变使用的theme。 -- 看起来类似于LocaleChangeInterceptor。

posted on 2016-12-05 10:15  LarryZeal  阅读(837)  评论(0编辑  收藏  举报

导航