1 @WebServlet("/RequestDemo2") 2 public class RequestDemo2 extends HttpServlet { 3 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 4 5 } 6 7 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 8 //演示獲取請求頭數據 9 10 //1.獲取所有請求頭名稱 11 Enumeration<String> headerNames = request.getHeaderNames(); 12 //2.遍歷 13 while(headerNames.hasMoreElements()){ 14 String name = headerNames.nextElement(); 15 //通過請求頭的名稱獲取請求頭的值 16 String value = request.getHeader(name); 17 System.out.println(name+"----"+value); 18 } 19 } 20 }
1 @WebServlet("/RequestDemo3") 2 public class RequestDemo3 extends HttpServlet { 3 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 4 5 } 6 7 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 8 //演示獲取請求頭數據:user-agent 9 String agent = request.getHeader("user-agent"); 10 //判度agent的瀏覽器版本 11 if(agent.contains("Chrome")){ 12 //谷歌 13 System.out.println("谷歌。。。。"); 14 }else if (agent.contains("Firefox")){ 15 System.out.println("火狐。。。"); 16 } 17 18 19 } 20 }
@WebServlet("/RequestDemo4") public class RequestDemo4 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //演示獲取請求頭數據:referer String referer = request.getHeader("referer"); System.out.println(referer); //防盜鏈 if(referer != null){ if(referer.contains("/request")){ //正常訪問 // System.out.println("正常訪問"); //顯示中文 response.setContentType("text/html;charset=utf-8"); response.getWriter().write("正常訪問"); }else{ //盜鏈 //System.out.println("盜鏈"); response.setContentType("text/html;charset=utf-8"); response.getWriter().write("存在盜鏈,不允許訪問"); } } } }