在项目开发中,我们经常需要记录用户是通过什么设备和操作系统来访问接口,以此来做不通的操作处理。尤其是公司软件针对多国用户,可以切换语言。我们后台经常需要根据语言来做不同的操作。
下面我们讲解如何通过实现HandlerMethodArgumentResolver的方法来实现用户访问接口时的设备信息
首先我们们需要准备一些必要的jar包
eu.bitwalker
UserAgentUtils
1.21
org.projectlombok
lombok
1.18.6
provided
org.apache.commons
commons-lang3
3.9
首先我给出一个获取用户的IP地址的工具类
package com.hongyu.studypay.untils;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.servlet.http.HttpServletRequest;
public class IpUtils {
/**
* 获取IP地址
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("HTTP_CLIENT_IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("HTTP_X_CONNECTING_IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("X-Real-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
String localIp = "127.0.0.1";
String localIpv6 = "0:0:0:0:0:0:0:1";
if (ipAddress.equals(localIp) || ipAddress.equals(localIpv6)) {
// 根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
ipAddress = inet.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
String ipSeparate = ",";
int ipLength = 15;
if (ipAddress != null && ipAddress.length() > ipLength) {
if (ipAddress.indexOf(ipSeparate) > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(ipSeparate));
}
}
return ipAddress;
}
}
下面我们需要定义一个实体类用来接收设备的相关信息
import java.io.Serializable;
import java.util.Locale;
import lombok.Data;
@Data
public class UserInfoVo implements Serializable {
private Locale locale;// 用户设备的语言相关信息
private String userIp; // 客户端ip
private String operatingSystemName; //操作系统类型
private String operatingSystemType;
private String deviceType; //访问设备名称
private String browserName;//浏览器名称
private String browserType;//浏览器类型
private String browserVersion;//浏览器版本
}
下面我们讲自定义参数解析器的实现
/**
* 获取用户访问网站使用的设备信息
* @author Administrator
*
*/
@Component
public class UserInfoResovler implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return UserInfoVo.class.isAssignableFrom( parameter.getParameterType() );
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
HttpServletRequest request = webRequest.getNativeRequest( HttpServletRequest.class );
String agent = request.getHeader("User-Agent");
//解析agent字符串
UserAgent userAgent = UserAgent.parseUserAgentString(agent);
//获取浏览器对象
Browser browser = userAgent.getBrowser();
//获取操作系统对象
OperatingSystem operatingSystem = userAgent.getOperatingSystem();
String lang = null;
Cookie[] cookie = request.getCookies();
if (cookie != null) {
for (int i = 0; i < cookie.length; i++) {
if ("locale".equalsIgnoreCase( cookie[ i ].getName() )) {
lang = cookie[ i ].getValue();
break;
}
}
}
String[] langArr = StringUtils.defaultIfBlank(lang,"").split( "_" );
Locale locale = langArr.length == 2 ? new Locale(langArr[0], langArr[1]) : RequestContextUtils.getLocale(request);
UserInfoVo userEnvVo = new UserInfoVo();
userEnvVo.setUserIp(IpUtils.getIpAddr(request));
userEnvVo.setLocale( locale );
userEnvVo.setOperatingSystemName(operatingSystem.getName());
userEnvVo.setOperatingSystemType(operatingSystem.getGroup().getName());
userEnvVo.setDeviceType(operatingSystem.getDeviceType().getName());
userEnvVo.setBrowserName(browser.getName());
userEnvVo.setBrowserType(browser.getBrowserType().getName());
userEnvVo.setBrowserVersion(userAgent.getBrowserVersion().getVersion());
return userEnvVo;
}
}
WebMvcConfigurerAdapter是Spring内部的一种配置方式
采用JavaBean的形式来代替传统的xml配置文件形式进行针对框架个性化定制
@SuppressWarnings("deprecation")
@Configuration
public class ApplicationWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
@Bean
public UserInfoResovler userEnvArgumentResolver() {
return new UserInfoResovler();
}
@Override
public void addArgumentResolvers(List argumentResolvers) {
argumentResolvers.add(userEnvArgumentResolver());
}
}
以上代码完成后我们就可以来测试下效果了
@PostMapping("headerInfo")
public Object TestInfo(UserInfoVo userEnvVo) {
System.out.println("访问该接口的用户设备信息"+JSON.toJSONString(userEnvVo));
return userEnvVo;
}
执行该接口后打印的数据:
访问该接口的用户设备信息{"browserName":"Chrome","browserType":"Browser","browserVersion":"73.0.3683.86","deviceType":"Computer","locale":"zh_CN","operatingSystemName":"Windows 7","operatingSystemType":"Windows","userIp":"169.254.201.46"}
我们获取了操作系统的相关信息,浏览器的相关信息,IP地址,语言等等。