Javaweb学习笔记之HttpServletRequest(二):获取客户端浏览器的类型

package com.demo.b_request;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
@WebServlet("/RequestDemo2")
public class RequestDemo2 extends HttpServlet {

	/*
	 * 获取浏览器的类型
	 * 	火狐浏览器:userAgent = Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36
	 * 	谷歌浏览器:userAgent = Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0
	 * 	IE 浏览器:userAgent = Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko
	 */
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setContentType("text/html;charset=utf-8");
		
		// 获取请求头:user-agent
		String userAgent = request.getHeader("user-agent");
		System.out.println("userAgent:" + userAgent);
		
		// 判断用户使用的浏览器类型
		if (userAgent.contains("Firefox")){
			response.getWriter().write("你正在使用火狐浏览器");
		}else if (userAgent.contains("Chrome")){
			response.getWriter().write("你正在使用谷歌浏览器");
		}else if (userAgent.contains("Trident")){
			response.getWriter().write("你正在使用 IE 浏览器");
		}else{
			response.getWriter().write("你用啥浏览器,我也不知道!!");
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

 

你可能感兴趣的:(javaweb学习笔记)