用java写一段可以判断用户请求是ios还是mac还是window的代码
时间: 2023-06-15 19:03:34 浏览: 217
js判断手机系统是android还是ios
可以使用user-agent来判断用户请求的设备类型,以下是用Java实现的示例代码:
```java
import javax.servlet.http.HttpServletRequest;
public class UserAgentUtil {
public static String getOs(HttpServletRequest request) {
String userAgent = request.getHeader("User-Agent");
String os = "";
if (userAgent.toLowerCase().contains("windows")) {
os = "Windows";
} else if (userAgent.toLowerCase().contains("mac")) {
os = "Mac";
} else if (userAgent.toLowerCase().contains("iphone") || userAgent.toLowerCase().contains("ipad") || userAgent.toLowerCase().contains("ipod")) {
os = "iOS";
}
return os;
}
}
```
在Servlet中调用该方法,即可获取用户请求的设备类型:
```java
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String os = UserAgentUtil.getOs(request);
out.println("您的设备类型为:" + os);
}
}
```
阅读全文