判斷用戶端手機類型,並跳轉到相應的app下載頁面
實現的原理,是檢測瀏覽器的 USER-AGENT 這個header,然後根據Regex來確定用戶端類型。
如果都不匹配,Fallback回退策略是顯示對應的頁面,讓使用者自己選擇。
適合採用二維碼掃描方式下載APP:
JSP版本的代碼如下所示:其他服務端版本請百度搜尋。
<%@page import="java.util.regex.Matcher"%><%@page import="java.util.regex.Pattern"%><%@ page language="java" pageEncoding="UTF-8"%><%!// \b 是單詞邊界(連著的兩個(字母字元 與 非字母字元) 之間的邏輯上的間隔),字串在編譯時間會被轉碼一次,所以是 "\\b"// \B 是單詞內部邏輯間隔(連著的兩個字母字元之間的邏輯上的間隔)String androidReg = "\\bandroid|Nexus\\b";String iosReg = "ip(hone|od|ad)";Pattern androidPat = Pattern.compile(androidReg, Pattern.CASE_INSENSITIVE);Pattern iosPat = Pattern.compile(iosReg, Pattern.CASE_INSENSITIVE);public boolean likeAndroid(String userAgent){if(null == userAgent){userAgent = "";}// 匹配Matcher matcherAndroid = androidPat.matcher(userAgent);if(matcherAndroid.find()){return true;} else {return false;}}public boolean likeIOS(String userAgent){if(null == userAgent){userAgent = "";}// 匹配Matcher matcherIOS = iosPat.matcher(userAgent);if(matcherIOS.find()){return true;} else {return false;}}%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";//String userAgent = request.getHeader( "USER-AGENT" ).toLowerCase();System.out.println("userAgent: "+userAgent);if(null == userAgent){userAgent = "";}if(likeAndroid(userAgent)){System.out.println("likeAndroid: "+true);response.sendRedirect("http://m.jb51.net/download.jsp?platform=android");return;//request.getRequestDispatcher("/download.html").forward(request,response);} else if(likeIOS(userAgent)){System.out.println("likeIOS: "+true);response.sendRedirect("http://itunes.apple.com/us/app/id714751061");return;//request.getRequestDispatcher("/index.html").forward(request,response);}%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"><title>下載用戶端 - 永恒記憶</title><link href="css/style.css" rel="stylesheet" type="text/css" /></head><body><div class="p_down"><div><a href="index.html"><img src="images/p_logo.png" class="p_logo" /></a></div> <a href="itms-services://?action=download-manifest&url=http://m.jb51.net/upload/client/yhjyios.plist" class="apple download"><img src="images/p_down_apple.png" /></a><a href="http://m.jb51.net/download.jsp?platform=android" class="download"><img src="images/p_down_and.png" /></a></div></body></html>