您的位置:首页 > 理论基础 > 计算机网络

HttpServletRequest常用方法介绍

2016-10-30 00:00 459 查看
摘要: 我正在学习httpServletRequest接口,我怕我忘记了,所以就写篇文章记录下来!

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息