javascript
Spring Boot 使用 AOP 实现页面自适应
鑒于復(fù)雜頁面自適應(yīng)的難度,一般會(huì)做幾套模板分別適應(yīng)手機(jī)、平板、電腦等設(shè)備。使用 Spring Boot 開發(fā)單體應(yīng)用時(shí),一般會(huì)使用 Thymeleaf 模板,那么可以使用 AOP 技術(shù)來實(shí)現(xiàn)頁面自適應(yīng)。
如圖所示,與普通項(xiàng)目相比而言,我們需要攔截用戶的請(qǐng)求,獲取 Request 中的 Header 的 User-Agent 屬性,來判斷用戶的設(shè)備信息,然后修改 Controller 返回的頁面路徑,來適應(yīng)設(shè)備的頁面路徑,從而達(dá)到頁面自適應(yīng)的效果。
代碼實(shí)現(xiàn)
假設(shè)我們的靜態(tài)資源目錄如下
resources/|-- mobile/|-- index.html #手機(jī)版首頁|-- index.html #電腦版首頁1、添加 aop 的相關(guān)依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency>2、定義設(shè)備的枚舉類型 UserAgentTypeEnum.java
/*** UserAgentType 枚舉*/ public enum UserAgentTypeEnum {// 電腦PC(0),// 平板電腦TABLET(1),// 手機(jī)PHONE(2);private int code;UserAgentTypeEnum(int code){this.code = code;}public int getCode() {return code;} }3、添加 UserAgent 識(shí)別工具類
/*** User-Agent 工具*/ public class UserAgentTools {/*** 識(shí)別設(shè)備類型* @param userAgent 設(shè)備標(biāo)識(shí)* @return 設(shè)備類型*/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、添加切面處理邏輯,實(shí)現(xiàn)設(shè)備識(shí)別和頁面路徑修改,假設(shè) Controller 類包 cn.ictgu.controller 下
/*** AOP 實(shí)現(xiàn)頁面自適應(yīng)*/ @Aspect @Component @Log4j2 public class DeviceAdapter {private static final String MOBILE_PREFIX = "mobile/";/*** 切入點(diǎn):cn.ictgu.controller 下所有 @GetMapping 方法*/@Pointcut("execution(* cn.ictgu.controller..*(..)) && @annotation(org.springframework.web.bind.annotation.GetMapping)")public void controllerMethodPointcut() {}/*** 識(shí)別用戶請(qǐng)求的設(shè)備并返回對(duì)應(yīng)的頁面*/@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 的頁面自適應(yīng)就完成了。示例:
@GetMapping(value = "/index")public String index() {return "index";}手機(jī)訪問就會(huì)得到?mobile/index.html?的頁面,其他設(shè)備就會(huì)得到?index.html?的頁面。
轉(zhuǎn)載請(qǐng)注明出處,謝謝!
有興趣一起寫代碼的,可以?加入我們,基于 Spring Boot 2.x 版本的最佳實(shí)踐。項(xiàng)目及演示地址?http://im.ictgu.cn/
開源, 等你!
http://www.spring4all.com/article/169
總結(jié)
以上是生活随笔為你收集整理的Spring Boot 使用 AOP 实现页面自适应的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 利用反射过滤对象的null值
- 下一篇: GoldenGate单向复制配置(支持D