有时候需要我们的项目有多种主题来满足不同使用用户各种审美的需求。
本文目的:springboot框架下实现静态切换主题(需重启生效) 功能实现。不讲原理(Spring Web MVC framework themes),想知道原理自行百度(https://docs.spring.io/spring/docs/4.2.6.RELEASE/spring-framework-reference/htmlsingle/#mvc-themeresolver )
前提:需要抽离出项目的每种主题样式css文件,每种主题的样式文件单独存放
一、创建样式配置类
该类作用:读取你配置的主题
例如我的主题1配置文件名为:theme-theme1.properties(后文讲其内容)
application.properties配置 theme=theme1,
配置类的实现如下
@Configuration
public class ThemeConfig{
/*
* 在application.properties中指定主题配置文件(静态配置)
*/
@Value("${theme}")
private String theme;
/*
* 指定主题配置文件前缀,例如下文:theme-
*/
@Bean
public ResourceBundleThemeSource themeSource(){
ResourceBundleThemeSource ResourceBundleThemeSource = new ResourceBundleThemeSource();
ResourceBundleThemeSource.setBasenamePrefix("theme-");
ResourceBundleThemeSource.setDefaultEncoding("utf-8");
return ResourceBundleThemeSource;
}
/*
* 将读取到的静态配置写入FixedThemeResolver(springMVC固定模板)
*/
@Bean
public FixedThemeResolver themeResolver(){
FixedThemeResolver fixedThemeResolver = new FixedThemeResolver();
fixedThemeResolver.setDefaultThemeName(theme);
return fixedThemeResolver;
}
}
二、theme-theme1.properties内容
每一种主题创建一个theme-xxx.properties。
这里的内容就是你每种主题的css文件们和图片们
例如 theme-theme1.properties中配置:
css1=/themes/theme1/index.css
css2=/themes/theme1/login.css
img1=/themes/theme1/img/logo.png
....
三、jsp中如何引用我们配置文件中样式图片文件路径
首先jsp添加:<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
css引用方式:<link rel="stylesheet" href="<spring:theme code='styleSheet'/>" type="text/css"/>
其他方式: <body style="<spring:theme code='img'/>">...</body>
其中code值为theme-theme1.properties的key值
四、总结
总结起来,就是分为五步:
(1)项目抽离出每个主题的css样式
(2)把每种主题的css路径写入到自己的 theme-xxx.properties中
(3)springboot中创建配置类读取我们设置好的主题theme-xxx.properties文件
(4)jsp页面通过<spring:theme code='xxxx'/>标签来读取theme-xxx.properties中不同key的css文件
(5)需要切换样式,只需修改application.properties的theme值为xxx,重启项目即可
另 :动态切换也很简单大家可自行思考(可参考:https://blog.csdn.net/neweastsun/article/details/79213867)