栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java > SpringBoot

使用Spring Mobile实现网站移动端适配及更换主题

SpringBoot 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Spring Mobile实现网站移动端适配及更换主题

现在的网站,很多都有需要动态更换主题风格的需求,比如每到特殊节日,更换为带有节日气氛的主题。还有用户通过手机端浏览器访问,如果没有做移动端的适配,你的网站基本也是没办法看的。本文介绍了使用Spring Mobile实现网站移动端适配及动态更换网站主题风格。

Spring Mobile简介

Spring Mobile可以检测出当前请求使用的设备是PC、还是手机或者是平板以及用户设备是安卓平台还是iOS平台,然后根据请求设备的不同,返回适合该设备的视图。

引入Spring Mobile

如果你的项目是基于Spring Boot构建的,只需在项目中引入Spring Mobile的starter即可:


    org.springframework.boot
    spring-boot-starter-mobile
上代码

本文使用的是Thymeleaf模板引擎,其它模板引擎原理也是一样的。application.properties文件中Thymeleaf模板引擎的配置如下:

# THYMELEAF
spring.thymeleaf.cache=falsespring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.check-template=truespring.thymeleaf.check-template-location=truespring.thymeleaf.content-type=text/html
spring.thymeleaf.enabled=truespring.thymeleaf.encoding=UTF-8spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

创建controller:

@Controllerpublic class TestController {    @GetMapping("/test")    public String test() {        return "test";
    }
}

在/resources/templates目录下,新建default目录,用于存放PC端默认主题的视图。新建test.html文件:


    
    test这里是【PC端测试页面】

在/resources/templates目录下,新建theme-blue目录,用于存放PC端蓝色主题的视图。新建test.html文件:


    
    test这里是【PC端测试页面-蓝色主题】

在/resources/templates目录下,新建mobile目录,用于存放移动端默认主题的视图。新建test.html文件:


    
    test这里是【移动端测试页面】

在/resources/templates目录下,新建theme-mobile-blue目录,用于存放移动端蓝色主题的视图。新建test.html文件:


    
    test这里是【移动端测试页面-蓝色主题】

新建主题视图解析类ThemeViewResolver:

import org.apache.commons.lang3.StringUtils;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.beans.factory.annotation.Value;import org.springframework.mobile.device.Device;import org.springframework.mobile.device.DeviceUtils;import org.springframework.mobile.device.util.ResolverUtils;import org.springframework.mobile.device.view.LiteDeviceDelegatingViewResolver;import org.springframework.stereotype.Component;import org.springframework.web.context.request.RequestAttributes;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;import org.springframework.web.servlet.View;import org.springframework.web.servlet.ViewResolver;import org.thymeleaf.util.ClassLoaderUtils;import javax.annotation.PostConstruct;import javax.servlet.http.HttpServletRequest;import java.net.URL;import java.util.Locale;@Componentpublic class ThemeViewResolver extends LiteDeviceDelegatingViewResolver {    // PC端默认主题目录
    private static final String DEFAULT_NORMAL_THEME = "default/";    // 手机端默认主题目录
    private static final String DEFAULT_MOBILE_THEME = "mobile/";    // 平板端默认主题目录
    private static final String DEFAULT_TABLET_THEME = "mobile/";    // PC端当前主题目录
    private static final String CURRENT_NORMAL_THEME = "default/";    // 手机端当前主题目录
    private static final String CURRENT_MOBILE_THEME = "mobile/";    // 平板端当前主题目录
    private static final String CURRENT_TABLET_THEME = "mobile/";    @Value("${spring.thymeleaf.prefix}")    private String thymeleafPrefix;    @Value("${spring.thymeleaf.suffix}")    private String thymeleafSuffix;    public ThemeViewResolver(@Qualifier("thymeleafViewResolver") ViewResolver delegate) {        super(delegate);
    }    @PostConstruct
    public void init() {        // 是否支持回退
        // true表示如果找不到移动端视图,则使用PC端默认视图
        this.setEnableFallback(true);        this.setNormalPrefix(DEFAULT_NORMAL_THEME);        this.setMobilePrefix(DEFAULT_MOBILE_THEME);        this.setTabletPrefix(DEFAULT_TABLET_THEME);        // 设置的优先级要比ThymeleafViewResolver高,要在ThymeleafViewResolver之前解析
        this.setOrder(1);
    }    
    @Override
    protected String getDeviceViewNameInternal(String viewName) {
        RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) attrs).getRequest();
        Device device = DeviceUtils.getCurrentDevice(request);
        String resolvedViewName = viewName;
        String currentTheme = this.getNormalPrefix();        if (ResolverUtils.isNormal(device, null)) {
            currentTheme = StringUtils.isNotEmpty(CURRENT_NORMAL_THEME) ? appendTrailingSlash(CURRENT_NORMAL_THEME) : this.getNormalPrefix();
            resolvedViewName = currentTheme + viewName + this.getNormalSuffix();
        } else if (ResolverUtils.isMobile(device, null)) {
            currentTheme = StringUtils.isNotEmpty(CURRENT_MOBILE_THEME) ? appendTrailingSlash(CURRENT_MOBILE_THEME) : this.getMobilePrefix();
            resolvedViewName = currentTheme + viewName + this.getMobileSuffix();
        } else if (ResolverUtils.isTablet(device, null)) {
            currentTheme = StringUtils.isNotEmpty(CURRENT_TABLET_THEME) ? appendTrailingSlash(CURRENT_TABLET_THEME) : this.getTabletPrefix();
            resolvedViewName = currentTheme + viewName + this.getTabletSuffix();
        }        return this.stripTrailingSlash(resolvedViewName);
    }    @Override
    public View resolveViewName(String viewName, Locale locale) throws Exception {        // 获取当前设备对应的视图名
        String deviceViewName = this.getDeviceViewName(viewName);        // 检查设备视图模板是否存在
        boolean deviceViewExisted = checkViewExisted(deviceViewName);
        View view = null;        if (this.getEnableFallback() && !deviceViewExisted) {            // 启用回退功能
            // 如果设备视图模板不存在,则返回PC端默认视图
            String normalViewName = this.getNormalPrefix().concat(viewName).concat(this.getNormalSuffix());
            view = this.getViewResolver().resolveViewName(normalViewName, locale);
        } else {
            view = this.getViewResolver().resolveViewName(deviceViewName, locale);
        }        return view;
    }    public boolean checkViewExisted(String viewName) {
        String prefix = thymeleafPrefix.replace("classpath:/", StringUtils.EMPTY);
        String fullPath = prefix.concat(viewName).concat(thymeleafSuffix);
        URL url = ClassLoaderUtils.getClassLoader(this.getClass()).getResource(fullPath);        return url != null;
    }    private String stripTrailingSlash(String viewName) {        return viewName.endsWith("//") ? viewName.substring(0, viewName.length() - 1) : viewName;
    }    private String appendTrailingSlash(String themeName) {        return themeName.endsWith("/") ? themeName : themeName.concat("/");
    }
}

使用PC端访问:



使用移动端访问:



修改当前使用的主题为蓝色主题:

// PC端当前主题目录private static final String CURRENT_NORMAL_THEME = "theme-blue/";// 手机端当前主题目录private static final String CURRENT_MOBILE_THEME = "theme-mobile-blue/";// 平板端当前主题目录private static final String CURRENT_TABLET_THEME = "theme-mobile-blue/";

使用PC端访问:



使用移动端访问:



测试回退功能,删除theme-mobile-blue目录,因为找不到移动端蓝色主题视图,则回退使用PC端默认视图。

             

作者:jessehua

链接:https://www.jianshu.com/p/f9024eb3f252

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/235876.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号