JavaWeb项目中获取客户端类型

JavaWeb项目中获取客户端类型

从事JavaWeb项目的开发,总会遇到需要根据不同客户端给予不同响应的需求,这里介绍一个好用的工具包.


1.引入Maven依赖包

UserAgentUtils pom

   <!-- 最好使用最新版本的依赖,因为其中所有客户端的软件版本一直在更新中,使用最新的依赖才能准确的得到客户端的类型 -->
   <dependency>
   <groupId>eu.bitwalker</groupId>
   <artifactId>UserAgentUtils</artifactId>
   <version>1.21</version>
   </dependency>

2.创建一个自己的小工具类

	public final class ClientExamineUtil {

	private static final String UserAgentHeader =  "user-agent";

	/**
	 * 获取客户端代理对象header值
	 * @param request 
	 * @return
	 */
	public static String getUserAgent(HttpServletRequest request){
		return request.getHeader(UserAgentHeader);
	}

	/**
	 * 获取用户代理对象
	 * @return
	 */
	public static UserAgent getUserAgent(String userAgent){
		return UserAgent.parseUserAgentString(userAgent);
	}

	/**
	 * 获取设备类型
	 * @return
	 */
	public static DeviceType getDeviceType(String userAgent){
		return getUserAgent(userAgent).getOperatingSystem().getDeviceType();
	}

	/**
	 * 是否是PC
	 * @return
	 */
	public static boolean isPc(String userAgent){
		return DeviceType.COMPUTER.equals(getDeviceType(userAgent));
	}

	/**
	 * 是否是手机
	 * @return
	 */
	public static boolean isMobile(String userAgent){
		return DeviceType.MOBILE.equals(getDeviceType(userAgent));
	}

	/**
	 * 是否是平板
	 * @return
	 */
	public static boolean isTablet(String userAgent){
		return DeviceType.TABLET.equals(getDeviceType(userAgent));
	}

	/**
	 * 是否是手机和平板
	 * @return
	 */
	public static boolean isMobileOrTablet(String userAgent){
		DeviceType deviceType = getDeviceType(userAgent);
		return DeviceType.MOBILE.equals(deviceType) || DeviceType.TABLET.equals(deviceType);
		}
	}

3.现在就可以美美地判断请求那头是什么客户端了

当然,这个工具的用途不止于此,可以根据它现有的功能,实现很多自己想要的功能.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值