欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HttpServletRequest常用方法介绍

程序员文章站 2024-02-04 20:32:04
...

request.setCharacterEncoding("utf-8");        //设置请求的字符集,用户提交到servlet的数据以utf-8的形式

 

String user = request.getParameter("user");      //获取用户提交的数据.

 

String contentPath = request.getContextPath();获取项目的根目录!

 

Enumeration<String> en = request.getHeaderNames();  //获取请求头名称,是一组枚举数据,类型为String

 

String s = request.getHeader(obj.toString());   //通过头名称获取到请求的头.

 

以下是示例代码:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String user = request.getParameter("user");
		System.out.println("user" + user);
		int contentLength = request.getContentLength();
		System.out.println("contentLength:" + contentLength);
		String contentType = request.getContentType();
		String contentPath = request.getContextPath();
		System.out.println("contentType:" + contentType + "contentPath: " + contentPath);
		Enumeration<String> en = request.getHeaderNames();
		while(en.hasMoreElements()){
			Object obj = en.nextElement();
			String s = request.getHeader(obj.toString());
			System.out.println("obj=" + obj.toString() + "s= "+s);
		}
	}

以下是输出信息:

userruankun
contentLength:-1
contentType:null    contentPath: /mytb
obj=hosts= localhost:8080
obj=user-agent          s= Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0
obj=accept             s= text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
obj=accept-language              s= zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3
obj=accept-encoding            s= gzip, deflate
obj=referer            s= http://localhost:8080/mytb/
obj=connection             s= keep-alive
obj=upgrade-insecure-requests               s= 1

转载于:https://my.oschina.net/qkmc/blog/778124