Servlet-request之與請求頭相關的方法
阿新 • • 發佈:2019-01-02
/**
* @author CSDN_LQR
* @TODO request之與請求頭相關的方法
*/
public class ServletDemo2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// getHeaderTest(request);
// getHeaderNamesTest(request);
getHeadersTest(request);
}
/**
* 得到指定請求頭(該請求頭可能一個名字,多個值)
*
* @param request
*/
private void getHeadersTest(HttpServletRequest request) {
Enumeration<String> headers = request.getHeaders("accept-language");
while (headers.hasMoreElements()) {
String headerValue = headers.nextElement();
System.out.println(headerValue);
}
}
/**
* 得到所有請求頭名字
*
* @param request
*/
private void getHeaderNamesTest(HttpServletRequest request) {
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String header = headerNames.nextElement();
String headerValue = request.getHeader(header);
System.out.println(header + ":" + headerValue);
}
}
/**
* 得到指定請求頭
*
* @param request
*/
private void getHeaderTest(HttpServletRequest request) {
String userAgent = request.getHeader("User-Agent");
System.out.println("User-Agent:" + userAgent);
userAgent = userAgent.toLowerCase();
if (userAgent.contains("msie")) {
System.out.println("IE瀏覽器");
} else if (userAgent.contains("firefox")) {
System.out.println("火狐瀏覽器");
} else if (userAgent.contains("chrome")) {
System.out.println("谷歌瀏覽器");
} else if (userAgent.contains("oprea")) {
System.out.println("Opera瀏覽器");
} else {
System.out.println("其他瀏覽器");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}