專案需求:根據 User-Agent 自動判斷訪客是否為行動裝置,並導向對應版面(如 download.html 或 index.html)。參考天貓前端團隊分享的 PHP 正則,將其移植至 JSP 環境,實現高精準度的裝置識別。
<%@ page import="java.util.regex.Pattern, java.util.regex.Matcher" %>
<%!
// 手機裝置正則(不區分大小寫)
private static final String PHONE_REGEX =
"\\b(ip(hone|od)|android|opera m(ob|in)i"
+ "|windows (phone|ce)|blackberry"
+ "|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp"
+ "|laystation portable)|nokia|fennec|htc[-_]"
+ "|mobile|up\\.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
// 平板裝置正則
private static final String TABLET_REGEX =
"\\b(ipad|tablet|(Nexus 7)|up\\.browser"
+ "|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
private static final Pattern PHONE_PAT = Pattern.compile(PHONE_REGEX, Pattern.CASE_INSENSITIVE);
private static final Pattern TABLET_PAT = Pattern.compile(TABLET_REGEX, Pattern.CASE_INSENSITIVE);
public static boolean checkMobile(String userAgent) {
if (userAgent == null) userAgent = "";
Matcher mPhone = PHONE_PAT.matcher(userAgent);
Matcher mTablet = TABLET_PAT.matcher(userAgent);
return mPhone.find() || mTablet.find();
}
%>
<%@ page language="java" pageEncoding="UTF-8" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":"
+ request.getServerPort() + path + "/";
String userAgent = request.getHeader("User-Agent");
if (userAgent == null) userAgent = "";
if (checkMobile(userAgent)) {
response.sendRedirect(basePath + "download.html");
} else {
response.sendRedirect(basePath + "index.html");
}
%>
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<base href="<%=basePath%>">
<title>裝置偵測跳轉中...</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
<div style="min-height:500px; text-align:center; padding-top:200px;">
正在識別裝置並跳轉...<br>
<a href="<%=basePath%>index.html">若未自動跳轉請點這裡</a>
</div>
</body></html>
@WebFilter("/*")
public class DeviceFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
String ua = request.getHeader("User-Agent");
if (checkMobile(ua)) {
((HttpServletResponse)res).sendRedirect(request.getContextPath() + "/mobile/");
} else {
chain.doFilter(req, res);
}
}
}
正則法無法涵蓋所有新機型,企業級專案建議引入 WURFL 或 DeviceAtlas,提供裝置型號、螢幕尺寸、OS 版本等豐富屬性。
現代 Web 開發主流採用 RWD (Responsive Web Design),單一代碼庫透過 CSS Media Queries 適配所有裝置,避免維護多套版面、SEO 權重分散等問題。
\\b:單字邊界,避免部分匹配(如 "android" 不會匹配 "androidtv")Pattern.CASE_INSENSITIVE:忽略大小寫,User-Agent 大小寫不一[1-4][0-9]{2}x[1-4][0-9]{2}:匹配常見解析度格式(如 320x480)本方案移植自天貓實戰正則,精準度高、部署簡單,適合中小型專案快速實現行動裝置分流。大型系統建議升級為專業裝置識別服務或全面採用響應式設計。