java后台判断客户端是手机/PC并返回不同页面的实例
这个代码其实不是由我本人发现的,而是在翻看公司项目时无意间发现,觉得很实用所以拿出来大家分享。
框架:Struts2+spring+ibatis,
主要实现是依靠Http请求头Header中的"User-Agent"来完成,好了,废话不多说直接上代码。
Action中:
publicStringexecute(){
HttpServletRequestrequest=ServletActionContext.getRequest();
booleanisMoblie=JudgeIsMoblie(request);
if(isMoblie){
return"phone";
}
return"pc";
}
publicbooleanJudgeIsMoblie(HttpServletRequestrequest){
booleanisMoblie=false;
String[]mobileAgents={"iphone","android","phone","mobile",
"wap","netfront","java","operamobi","operamini","ucweb",
"windowsce","symbian","series","webos","sony",
"blackberry","dopod","nokia","samsung","palmsource","xda",
"pieplus","meizu","midp","cldc","motorola","foma",
"docomo","up.browser","up.link","blazer","helio","hosin",
"huawei","novarra","coolpad","webos","techfaith",
"palmsource","alcatel","amoi","ktouch","nexian",
"ericsson","philips","sagem","wellcom","bunjalloo","maui",
"smartphone","iemobile","spice","bird","zte-","longcos",
"pantech","gionee","portalmmm","jigbrowser","hiptop",
"benq","haier","^lct","320x320","240x320","176x220",
"w3c","acs-","alav","alca","amoi","audi","avan","benq",
"bird","blac","blaz","brew","cell","cldc","cmd-","dang",
"doco","eric","hipt","inno","ipaq","java","jigs","kddi",
"keji","leno","lg-c","lg-d","lg-g","lge-","maui","maxo",
"midp","mits","mmef","mobi","mot-","moto","mwbp","nec-",
"newt","noki","oper","palm","pana","pant","phil","play",
"port","prox","qwap","sage","sams","sany","sch-","sec-",
"send","seri","sgh-","shar","sie-","siem","smal","smar",
"sony","sph-","symb","t-mo","teli","tim-",/*"tosh",*/"tsm-",
"upg1","upsi","vk-v","voda","wap-","wapa","wapi","wapp",
"wapr","webc","winw","winw","xda","xda-",
"Googlebot-Mobile"};
if(request.getHeader("User-Agent")!=null){
for(StringmobileAgent:mobileAgents){
//这里本宝宝表示不怎么了解它的内部原理,但是知道个大概意思就得了。
if(request.getHeader("User-Agent").toLowerCase()
.indexOf(mobileAgent)>=0){
isMoblie=true;
break;
}
}
}
returnisMoblie;
}
Struts2
download/main.jsp download/productPH.jsp
好了,代码就只是这么多,木有了木有了。。。是不是感觉很简单的说,
虽然不是我写出来的,但是看到这个代码,也是有一种收获的,其实很多设置都是包含在请求头中的,因为不管是什么浏览器什么设备,它要通过http去调用一个请求,那么它就必定是有http协议,只要精通http协议,那么啥事都好办(表示本屌目前不懂http协议,而后努力学习学习,再来装逼)~~
以上这篇java后台判断客户端是手机/PC并返回不同页面的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。