servlet学习(二)request对象获取请求头信息

一、作用

封存了当前请求的所有请求信息

二、使用

获取请求头的信息包括:

1.请求行:请求方式 请求URL/URI 协议版本

//获取请求行
		     String method=req.getMethod();
		     StringBuffer url=req.getRequestURL();
		     String uri=req.getRequestURI();
		     String scheme=req.getScheme();
		     System.out.println("请求行:"+method+" "+uri+" "+scheme);

2.请求头:键值对

 //获取请求头
		     Enumeration enumeration=req.getHeaderNames();
		     System.out.println("请求头:");
		     while(enumeration.hasMoreElements()) {
		    	 String name=(String)enumeration.nextElement();
		    	 String value=req.getHeader(name);
		    	 System.out.println(name+" "+value);
		     }

3.请求数据

  //获取请求实体
		     req.getParameter("键名");       //返回指定的用户数据
		     req.getParameterValues("键名"); //返回同键不同值的string数组,如前台页面的多选框
		     req.getParameterNames();        //返回所有用户请求数据的枚举集合

运行结果:

请求行:GET /sx/s2 http
请求头:
host localhost:8080
connection keep-alive
cache-control max-age=0
upgrade-insecure-requests 1
user-agent Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
accept text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
accept-encoding gzip, deflate, br
accept-language zh-CN,zh;q=0.9

注意:如果是URL则:完整的浏览器访问地址(http://localhost:8080/sx/s2

注意:如果是URI则:虚拟项目名+对应的servlet名字(/sx/s2

注意:获取请求实体数据的时候,无论是get方式还是post方式,都是用 req.getParameter("键名"); 

猜你喜欢

转载自blog.csdn.net/weixin_40327259/article/details/83277006
今日推荐