欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JSP中实现判断客户端手机类型并跳转到app下载页面

程序员文章站 2023-10-27 22:37:58
判断客户端手机类型,并跳转到相应的app下载页面 实现的原理,是检测浏览器的 user-agent 这个header,然后根据正则表达式来确定客户端类型。 如果都不匹配...

判断客户端手机类型,并跳转到相应的app下载页面

实现的原理,是检测浏览器的 user-agent 这个header,然后根据正则表达式来确定客户端类型。

如果都不匹配,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>