点赞再看,养成习惯。
Theme,就是主题,点一下就给网站更换一个主题,相信大家都用过类似功能,这个其实和前面所说的国际化功能很像,代码其实也很像,今天我们就来捋一捋。
1.一键换肤
来做一个简单的需求,假设我的页面上有三个按钮,点击之后就能一键换肤,像下面这样:
我们来看下这个需求怎么实现。
首先三个按钮分别对应了三个不同的样式,我们先把这三个不同的样式定义出来,分别如下:
blue.css:
body{
background-color: #05e1ff;
}
green.css:
body{
background-color: #aaff9c;
}
red.css:
body{
background-color: #ff0721;
}
主题的定义,往往是一组样式,因此我们一般都是在一个 properties 文件中将同一主题的样式配置在一起,这样方便后期加载。
所以接下来我们在 resources 目录下新建 theme 目录,然后在 theme 目录中创建三个文件,内容如下:
blue.properties:
index.body=/css/blue.css
green.properties:
index.body=/css/green.css
red.properties:
index.body=/css/red.css
在不同的 properties 配置文件中引入不同的样式,但是样式定义的 key 都是 index.body,这样方便后期在页面中引入。
接下来在 SpringMVC 容器中配置三个 Bean,如下:
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor">
<property name="paramName" value="theme"/>
</bean>
</mvc:interceptor>
</mvc:interceptors>
<bean id="themeSource" class="org.springframework.ui.context.support.ResourceBundleThemeSource">
<property name="basenamePrefix" value="theme."/>
</bean>
<bean id="themeResolver" class="org.springframework.web.servlet.theme.SessionThemeResolver">
<property name="defaultThemeName" value="blue"/>
</bean>
首先配置拦截器 ThemeChangeInterceptor,这个拦截器用来解析主题参数,参数的 key 为 theme,例如请求地址是 /index?theme=blue,该拦截器就会自动设置系统主题为 blue。当然也可以不配置拦截器,如果不配置的话,就可以单独提供一个修改主题的接口,然后手动修改主题,类似下面这样:
@Autowired
private ThemeResolver themeResolver;
@RequestMapping(path =