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("存在盗链,不允许访问"); } } } }