Spring最近换域名了,去转转,发现了一个有意思的项目:spring mobile。

http://projects.spring.io/spring-mobile/

这个项目有很多实用的功能,如识别访问我们网站的设备是什么类型的(手机,平板,PC),据域名或者url来切换不同访问内容,据不同的访问设备转到不同的view中。

识别访问设备类型的核心代码在org.springframework.mobile.device.LiteDeviceResolver 类中,这个类实际上根据http请求头部的User-Agent的内容来判断设备到底是哪种类型的。

可以看到,这个类实际上是很简单的。不过字符串的匹配算法可能可以优化下。

[java] view
plain
copy

  1. public class LiteDeviceResolver implements DeviceResolver {
  2. private final List<String> mobileUserAgentPrefixes = new ArrayList<String>();
  3. private final List<String> mobileUserAgentKeywords = new ArrayList<String>();
  4. private final List<String> tabletUserAgentKeywords = new ArrayList<String>();
  5. private final List<String> normalUserAgentKeywords = new ArrayList<String>();
  6. public LiteDeviceResolver() {
  7. init();
  8. }
  9. public LiteDeviceResolver(List<String> normalUserAgentKeywords) {
  10. init();
  11. this.normalUserAgentKeywords.addAll(normalUserAgentKeywords);
  12. }
  13. public Device resolveDevice(HttpServletRequest request) {
  14. String userAgent = request.getHeader("User-Agent");
  15. // UserAgent keyword detection of Normal devices
  16. if (userAgent != null) {
  17. userAgent = userAgent.toLowerCase();
  18. for (String keyword : normalUserAgentKeywords) {
  19. if (userAgent.contains(keyword)) {
  20. return resolveFallback(request);
  21. }
  22. }
  23. }
  24. // UAProf detection
  25. if (request.getHeader("x-wap-profile") != null || request.getHeader("Profile") != null) {
  26. return LiteDevice.MOBILE_INSTANCE;
  27. }
  28. // User-Agent prefix detection
  29. if (userAgent != null && userAgent.length() >= 4) {
  30. String prefix = userAgent.substring(0, 4).toLowerCase();
  31. if (mobileUserAgentPrefixes.contains(prefix)) {
  32. return LiteDevice.MOBILE_INSTANCE;
  33. }
  34. }
  35. // Accept-header based detection
  36. String accept = request.getHeader("Accept");
  37. if (accept != null && accept.contains("wap")) {
  38. return LiteDevice.MOBILE_INSTANCE;
  39. }
  40. // UserAgent keyword detection for Mobile and Tablet devices
  41. if (userAgent != null) {
  42. userAgent = userAgent.toLowerCase();
  43. // Android special case
  44. if (userAgent.contains("android") && !userAgent.contains("mobile")) {
  45. return LiteDevice.TABLET_INSTANCE;
  46. }
  47. // Kindle Fire special case
  48. if (userAgent.contains("silk") && !userAgent.contains("mobile")) {
  49. return LiteDevice.TABLET_INSTANCE;
  50. }
  51. for (String keyword : tabletUserAgentKeywords) {
  52. if (userAgent.contains(keyword)) {
  53. return LiteDevice.TABLET_INSTANCE;
  54. }
  55. }
  56. for (String keyword : mobileUserAgentKeywords) {
  57. if (userAgent.contains(keyword)) {
  58. return LiteDevice.MOBILE_INSTANCE;
  59. }
  60. }
  61. }
  62. // OperaMini special case
  63. @SuppressWarnings("rawtypes")
  64. Enumeration headers = request.getHeaderNames();
  65. while (headers.hasMoreElements()) {
  66. String header = (String) headers.nextElement();
  67. if (header.contains("OperaMini")) {
  68. return LiteDevice.MOBILE_INSTANCE;
  69. }
  70. }
  71. return resolveFallback(request);
  72. }
  73. // subclassing hooks
  74. /**
  75. * List of user agent prefixes that identify mobile devices.
  76. * Used primarily to match by operator or handset manufacturer.
  77. */
  78. protected List<String> getMobileUserAgentPrefixes() {
  79. return mobileUserAgentPrefixes;
  80. }
  81. /**
  82. * List of user agent keywords that identify mobile devices.
  83. * Used primarily to match by mobile platform or operating system.
  84. */
  85. protected List<String> getMobileUserAgentKeywords() {
  86. return mobileUserAgentKeywords;
  87. }
  88. /**
  89. * List of user agent keywords that identify tablet devices.
  90. * Used primarily to match by tablet platform or operating system.
  91. */
  92. protected List<String> getTabletUserAgentKeywords() {
  93. return tabletUserAgentKeywords;
  94. }
  95. /**
  96. * List of user agent keywords that identify normal devices.
  97. * Any items in this list take precedence over the mobile and
  98. * tablet user agent keywords, effectively overriding those.
  99. */
  100. protected List<String> getNormalUserAgentKeywords() {
  101. return normalUserAgentKeywords;
  102. }
  103. /**
  104. * Initialize this device resolver implementation.
  105. * Registers the known set of device signature strings.
  106. * Subclasses may override to register additional strings.
  107. */
  108. protected void init() {
  109. getMobileUserAgentPrefixes().addAll(Arrays.asList(KNOWN_MOBILE_USER_AGENT_PREFIXES));
  110. getMobileUserAgentKeywords().addAll(Arrays.asList(KNOWN_MOBILE_USER_AGENT_KEYWORDS));
  111. getTabletUserAgentKeywords().addAll(Arrays.asList(KNOWN_TABLET_USER_AGENT_KEYWORDS));
  112. }
  113. /**
  114. * Fallback called if no mobile device is matched by this resolver.
  115. * The default implementation of this method returns a "normal" {@link Device} that is neither mobile or a tablet.
  116. * Subclasses may override to try additional mobile or tablet device matching before falling back to a "normal" device.
  117. */
  118. protected Device resolveFallback(HttpServletRequest request) {
  119. return LiteDevice.NORMAL_INSTANCE;
  120. }
  121. // internal helpers
  122. private static final String[] KNOWN_MOBILE_USER_AGENT_PREFIXES = new String[] { "w3c ", "w3c-", "acs-", "alav",
  123. "alca", "amoi", "audi", "avan", "benq", "bird", "blac", "blaz", "brew", "cell", "cldc", "cmd-", "dang",
  124. "doco", "eric", "hipt", "htc_", "inno", "ipaq", "ipod", "jigs", "kddi", "keji", "leno", "lg-c", "lg-d",
  125. "lg-g", "lge-", "lg/u", "maui", "maxo", "midp", "mits", "mmef", "mobi", "mot-", "moto", "mwbp", "nec-",
  126. "newt", "noki", "palm", "pana", "pant", "phil", "play", "port", "prox", "qwap", "sage", "sams", "sany",
  127. "sch-", "sec-", "send", "seri", "sgh-", "shar", "sie-", "siem", "smal", "smar", "sony", "sph-", "symb",
  128. "t-mo", "teli", "tim-", "tosh", "tsm-", "upg1", "upsi", "vk-v", "voda", "wap-", "wapa", "wapi", "wapp",
  129. "wapr", "webc", "winw", "winw", "xda ", "xda-" };
  130. private static final String[] KNOWN_MOBILE_USER_AGENT_KEYWORDS = new String[] { "blackberry", "webos", "ipod",
  131. "lge vx", "midp", "maemo", "mmp", "mobile", "netfront", "hiptop", "nintendo DS", "novarra", "openweb",
  132. "opera mobi", "opera mini", "palm", "psp", "phone", "smartphone", "symbian", "up.browser", "up.link",
  133. "wap", "windows ce" };
  134. private static final String[] KNOWN_TABLET_USER_AGENT_KEYWORDS = new String[] { "ipad", "playbook", "hp-tablet",
  135. "kindle" };
  136. }

Spring Mobile是如何判断访问设备的类型的的更多相关文章

  1. Java判断访问设备为手机、微信、PC工具类

    package com.lwj.util; import javax.servlet.http.HttpServletRequest; /** * 判断访问设备为PC或者手机--工具类 * * @de ...

  2. JS判断访问设备、客户端操作系统类型

    先给出一个实例:判断windows.linux.android 复制以下代码另存为html文件即可. <html> <head> <title>判断操作系统< ...

  3. [转]JS判断访问设备、客户端操作系统类型

    本文转自:http://www.cnblogs.com/duanguyuan/p/3534470.html 先给出一个实例:判断windows.linux.android 复制以下代码另存为html文 ...

  4. JS判断访问设备(userAgent)加载不同页面 JS判断客户端操作系统类型(platform)

    //平台.设备和操作系统 var system ={ win : false, mac : false, xll : false }; //检测平台 var p = navigator.platfor ...

  5. PHP和js判断访问设备是否是微信浏览器实例

    PHP和js判断访问设备是否是微信浏览器实例,代码非常精简,适合新手学习. js判断是否是微信浏览器: 1 function is_weixin() { 2 var ua = window.navig ...

  6. 判断访问浏览器客户端类型(pc,mac,ipad,iphone,android)

    <script type="text/javascript"> //平台.设备和操作系统 var system = { win: false, mac: false, ...

  7. JS判断访问设备是移动设备还是pc

    <scripttype="text/javascript"> function browserRedirect() { var sUserAgent= navigato ...

  8. 如何判断 ios设备的类型(iphone,ipod,ipad)

    功能函数: -(bool)checkDevice:(NSString*)name { NSString* deviceType = [UIDevice currentDevice].model; NS ...

  9. Spring Mobile——探测客户端设备和系统

    Spring Mobile--探测客户端设备和系统 今天闲来无事,浏览Spring的官方网站,发现了Spring Mobile项目,之前也看到过,还以为是针对手机端的项目,并没有细看.今天仔细看了一下 ...

随机推荐

  1. android -- 蓝牙 bluetooth (一) 入门

    前段时间在 网上看了一些关于android蓝牙的文章,发现大部分是基于老版本(4.1以前含4.1)的源码,虽然无碍了解蓝牙的基本原理和工作流程,但对着4.2.2的代码看起来总是有些遗憾.所以针对4.2 ...

  2. 【Hibernate】双向多对多Set查询

    一个计划对于多个竞价,一个竞价对应多个计划. 1.实体 /** * @author Tidy * @Description 计划 */ public class EbgStockPlanContent ...

  3. 2080夹角有多大II

    寻人启事:2014级新生看过来! 夹角有多大II Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Ot ...

  4. Hibernate 笔记1

    Hibernate表generator标签的作用,如下图,

  5. [javascript]一种兼容性比较好的简单拖拽

    作为一个马上要找工作.非计算机专业.热爱前端的大四狗,最近开始疯狂写demo.看书,准备九.十月份的校招. 晚上用js实现了一个比较简单(low)的拖拽效果,初步测试兼容性还是不错的,于是写一段小博文 ...

  6. hdu3483之二项式展开+矩阵快速幂

    A Very Simple Problem Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Ot ...

  7. NodeJS用Express建立project

    1.通过下面命令建立站点基本结构: <span style="margin: 0px; padding: 0px; font-family: Verdana, Arial, Helve ...

  8. word2vec 中的数学原理具体解释(五)基于 Negative Sampling 的模型

      word2vec 是 Google 于 2013 年开源推出的一个用于获取 word vector 的工具包,它简单.高效,因此引起了非常多人的关注. 因为 word2vec 的作者 Tomas ...

  9. iOS9适配系列教程

    链接地址:http://www.open-open.com/lib/view/open1443194127763.html 中文快速导航: iOS9网络适配_ATS:改用更安全的HTTPS(见Demo ...

  10. HDOJ 1384 差分约束

    结题报告合集请戳:http://972169909-qq-com.iteye.com/blog/1185527 /*题意:求符合题意的最小集合的元素个数 题目要求的是求的最短路, 则对于 不等式 f( ...