SpringBoot切换项目主题样式功能实现

有时候需要我们的项目有多种主题来满足不同使用用户各种审美的需求。

本文目的: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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值