當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring Boot 使用 AOP 实现页面自适应
生活随笔
收集整理的這篇文章主要介紹了
Spring Boot 使用 AOP 实现页面自适应
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
鑒于復雜頁面自適應的難度,一般會做幾套模板分別適應手機、平板、電腦等設備。使用 Spring Boot 開發單體應用時,一般會使用 Thymeleaf 模板,那么可以使用 AOP 技術來實現頁面自適應。
如圖所示,與普通項目相比而言,我們需要攔截用戶的請求,獲取 Request 中的 Header 的 User-Agent 屬性,來判斷用戶的設備信息,然后修改 Controller 返回的頁面路徑,來適應設備的頁面路徑,從而達到頁面自適應的效果。
代碼實現
假設我們的靜態資源目錄如下
resources/|-- mobile/|-- index.html #手機版首頁|-- index.html #電腦版首頁1、添加 aop 的相關依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency>2、定義設備的枚舉類型 UserAgentTypeEnum.java
/*** UserAgentType 枚舉*/ public enum UserAgentTypeEnum {// 電腦PC(0),// 平板電腦TABLET(1),// 手機PHONE(2);private int code;UserAgentTypeEnum(int code){this.code = code;}public int getCode() {return code;} }3、添加 UserAgent 識別工具類
/*** User-Agent 工具*/ public class UserAgentTools {/*** 識別設備類型* @param userAgent 設備標識* @return 設備類型*/public static Integer recognize(String userAgent){if(Pattern.compile("(Windows Phone|Android|iPhone|iPod)").matcher(userAgent).find()){return UserAgentTypeEnum.PHONE.getCode();}if(Pattern.compile("(iPad)").matcher(userAgent).find()){return UserAgentTypeEnum.TABLET.getCode();}return UserAgentTypeEnum.PC.getCode();}}4、添加切面處理邏輯,實現設備識別和頁面路徑修改,假設 Controller 類包 cn.ictgu.controller 下
/*** AOP 實現頁面自適應*/ @Aspect @Component @Log4j2 public class DeviceAdapter {private static final String MOBILE_PREFIX = "mobile/";/*** 切入點:cn.ictgu.controller 下所有 @GetMapping 方法*/@Pointcut("execution(* cn.ictgu.controller..*(..)) && @annotation(org.springframework.web.bind.annotation.GetMapping)")public void controllerMethodPointcut() {}/*** 識別用戶請求的設備并返回對應的頁面*/@Around("controllerMethodPointcut()")public String around(ProceedingJoinPoint joinPoint) {ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();if (attributes != null) {try {HttpServletRequest request = attributes.getRequest();String userAgent = request.getHeader("User-Agent");log.info(userAgent);Integer deviceType = UserAgentTools.recognize(userAgent);String path = (String) joinPoint.proceed();return deviceType == UserAgentTypeEnum.PHONE.getCode() ? MOBILE_PREFIX + path : path;} catch (Throwable e) {e.printStackTrace();}}throw new RuntimeException("DeviceAdapter,ServletRequestAttributes is null!");}}5、至此,基于 AOP 的頁面自適應就完成了。示例:
@GetMapping(value = "/index")public String index() {return "index";}手機訪問就會得到?mobile/index.html?的頁面,其他設備就會得到?index.html?的頁面。
轉載請注明出處,謝謝!
有興趣一起寫代碼的,可以?加入我們,基于 Spring Boot 2.x 版本的最佳實踐。項目及演示地址?http://im.ictgu.cn/
開源, 等你!
http://www.spring4all.com/article/169
總結
以上是生活随笔為你收集整理的Spring Boot 使用 AOP 实现页面自适应的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 利用反射过滤对象的null值
- 下一篇: JS----文档对象模型