1、什么是http协议
http协议: 对浏览器客户端 和 服务器端 之间数据传输的格式规范
2、查看http协议的工具
1)使用火狐的firebug插件(右键->firebug->网络) 2)使用谷歌的“审查元素” 3)使用系统自带的telnet工具(远程访问工具) a)telnet localhost 8080 访问tomcat服务器 b)ctrl+] 回车 可以看到回显 c)输入请求内容
3 Http请求
GET /day09/hello HTTP/1.1 -请求行 Host: localhost:8080 --请求头(多个key-value对象) User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: zh-cn,en-us;q=0.8,zh;q=0.5,en;q=0.3 Accept-Encoding: gzip, deflate Connection: keep-alive --一个空行 name=eric&password=123456 --(可选)实体内容
3.1 请求行
GET /day09/hello HTTP/1.1 #http协议版本 (1.1) http1.0:当前浏览器客户端与服务器端建立连接之后,只能发送一次请求,一次请求之后连接关闭。 http1.1:当前浏览器客户端与服务器端建立连接之后,可以在一次连接中发送多次请求。(基本都使用1.1) (比如发送图片,不同的图片会占用一次的请求)(但是相同的图片就会减少请求的次数,因为浏览器会有缓存)(发送三张不同的图片,有四次请求,第一次想页面请求,其他的三次向图片请求)
#请求资源 URL: 统一资源定位符。http://localhost:8080/day09/testImg.html。只能定位互联网资源。是URI的子集。 URI: 统一资源标记符。/day09/hello。用于标记任何资源。可以是本地文件系统,局域网的资源 (//192.168.14.10/myweb/index.html),可以是互联网。
#请求方式 常见的请求方式: GET 、 POST、 HEAD、 TRACE、 PUT、 CONNECT 、DELETE 常用的请求方式: GET 和 POST
表单提交:<form action="提交地址" method="GET/POST"> </form>
GET vs POST 区别
1)GET方式提交 a)地址栏(URI)会跟上参数数据。以?开头,多个参数之间以&分割。 GET /day09/testMethod.html?name=eric&password=123456 HTTP/1.1 Host: localhost:8080 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: zh-cn,en-us;q=0.8,zh;q=0.5,en;q=0.3 Accept-Encoding: gzip, deflate Referer: http://localhost:8080/day09/testMethod.html Connection: keep-alive b)GET提交参数数据有限制,不超过1KB。 c)GET方式不适合提交敏感密码。 d)注意: 浏览器直接访问的请求,默认提交方式是GET方式 2)POST方式提交 a)参数不会跟着URI后面。参数而是跟在请求的实体内容中。没有?开头,多个参数之间以&分割。 POST /day09/testMethod.html HTTP/1.1 Host: localhost:8080 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: zh-cn,en-us;q=0.8,zh;q=0.5,en;q=0.3 Accept-Encoding: gzip, deflate Referer: http://localhost:8080/day09/testMethod.html Connection: keep-alive name=eric&password=123456 b)POST提交的参数数据没有限制。 c)POST方式提交敏感数据。
3.2请求头
Accept: text/html,image/* -- 浏览器接受的数据类型 Accept-Charset: ISO-8859-1 -- 浏览器接受的编码格式 Accept-Encoding: gzip,compress --浏览器接受的数据压缩格式 Accept-Language: en-us,zh- --浏览器接受的语言 Host: www.it315.org:80 --(必须的)当前请求访问的目标地址(主机:端口) If-Modified-Since: Tue, 11 Jul 2000 18:23:51 GMT --浏览器最后的缓存时间 Referer: http://www.it315.org/index.jsp -- 当前请求来自于哪里 User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0) --浏览器类型 Cookie:name=eric -- 浏览器保存的cookie信息 Connection: close/Keep-Alive -- 浏览器跟服务器连接状态。close: 连接关闭 keep-alive:保存连接。 Date: Tue, 11 Jul 2000 18:23:51 GMT -- 请求发出的时间
3.3 实体内容
只有POST提交的参数会放到实体内容中
3.4 HttpServletRequest对象 HttpServletRequest对象作用是用于获取请求数据。 (全部的请求都封装到这里HttpServletRequest) 核心的API: 请求行: request.getMethod(); 请求方式 request.getRequetURI() / request.getRequetURL() 请求资源 request.getProtocol() 请求http协议版本 请求头: request.getHeader("名称") 根据请求头获取请求值 request.getHeaderNames() 获取所有的请求头名称 实体内容: request.getInputStream() 获取实体内容数据RequestDeom1.java 输出请求的方式,请求的资源,http协议
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("请求方式:"+request.getMethod());//请求方式
System.out.println("URI:"+request.getRequestURI());//请求资源
System.out.println("URL:"+request.getRequestURL());
System.out.println("http协议版本:"+request.getProtocol());//http协议
}
输出: 请求方式:GET //浏览器默认的提交方式就是get方式 URI:/day10/RequestDeom1 URL:http://localhost:8080/day10/RequestDeom1 http协议版本:HTTP/1.1
3.2 请求头 String host = request.getHeader("Host"); //根据头名称的到头的内容 System.out.println(host);
boolean hasMoreElements() 测试此枚举是否包含更多的元素。 E nextElement() 如果此枚举对象至少还有一个可提供的元素,则返回此枚举的下一个元素。
得到所有的请求头:
//遍历所有请求头
Enumeration<String> enums = request.getHeaderNames(); //得到所有的请求头名称列表
while(enums.hasMoreElements()){//判断是否有下一个元素
String headerName = enums.nextElement(); //取出下一个元素
String headerValue = request.getHeader(headerName);
System.out.println(headerName+":"+headerValue);
}
}
输出: host:localhost:8080 user-agent:Mozilla/5.0 (Windows NT 6.1; WOW64; rv:57.0) Gecko/20100101 Firefox/57.0 accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 accept-language:zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2 accept-encoding:gzip, deflate connection:keep-alive upgrade-insecure-requests:1请求的实体内容使用doPost接收post发送的内容,post接收实体内容:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>测试请求方式</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<h3>POST方式提交</h3>
<form action="/day10/RequestDeom1" method="POST"> <!-- 请求名称加地址 :action="/day10/RequestDeom1"-->
用户名:<input type="text" name="name"/><br/>
密码:<input type="password" name="password"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
为了接收POST方式提交的请求:
protected void doPost(HttpServletRequest request, HttpServletResponse resp)
throws ServletException, IOException {
/**
* 3.3 请求的实体内容
*/
InputStream in = request.getInputStream(); //得到实体内容
byte[] buf = new byte[1024];
int len = 0;
while( (len=in.read(buf))!=-1 ){
String str = new String(buf,0,len);
System.out.println(str);
}
}
执行http://localhost:8080/day10/RequestDeom1 输入:eric 123456 输出:name=eric&password=123456
传递的请求参数如何获取 GET方式: 参数放在URI后面 POST方式: 参数放在实体内容中 获取GET方式参数: request.getQueryString(); 获取POST方式参数: request.getInputStream();------分别使用doPost和doGet方式获得:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>测试请求方式</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<h3>GET方式提交</h3>
<form action="/day10/RequestDeom5" method="GET">
用户名:<input type="text" name="name"/><br/>
密码:<input type="password" name="password"/><br/>
<input type="submit" value="提交"/>
</form>
<hr/>
<h3>POST方式提交</h3>
<form action="/day10/RequestDeom5" method="POST"> <!-- 请求名称加地址 :action="/day10/RequestDeom5"-->
用户名:<input type="text" name="name"/><br/>
密码:<input type="password" name="password"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
public class RequestDeom5 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("GET方式");
String value = request.getQueryString();
System.out.println(value);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("POST方式");
InputStream in = request.getInputStream();
byte[] buf = new byte[1024];
int len=0;
while((len=in.read(buf))!=-1){
System.out.println(new String(buf,0,len));
}
}
}
执行http://localhost:8080/day10/RequestDeom5 输入:eric 123456 eric 123456 输出: GET方式 name=eric&password=123456 POST方式 name=eric&password=123456
问题:但是以上两种不通用,而且获取到的参数还需要进一步地解析。 所以可以使用统一方便的获取参数的方式: 核心的API: request.getParameter("参数名"); 根据参数名获取参数值(注意,只能获取一个值的参数) request.getParameterValue("参数名“);根据参数名获取参数值(可以获取多个值的参数) request.getParameterNames(); 获取所有参数名称列表
String name = request.getParameter("name");
String password = request.getParameter("password");
System.out.println(name+"="+password);
System.out.println("=============================");
Enumeration<String> enums = request.getParameterNames();
while( enums.hasMoreElements() ){
String paramName = enums.nextElement();
if("hobit".equals(paramName)) {
System.out.print(paramName+": ");
String[] hobits = request.getParameterValues("hobit");
for(String h: hobits){
System.out.print(h+",");
}
System.out.println();
}
else{
String paramValue = request.getParameter(paramName);
System.out.println(paramName+"="+paramValue);
}
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>请求参数传递和接收问题</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!-- 编码格式为utf-8 -->
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<body>
<h3>GET方式提交</h3>
<form action="/day10/RequestDeom5" method="GET">
用户名:<input type="text" name="name"/><br/>
密码:<input type="password" name="password"/><br/>
性别:
<input type="radio" name="gender" value="男"/>男
<input type="radio" name="gender" value="女"/>女<br/>
籍贯:
<select name="jiguan">
<option value="广东">广东</option>
<option value="广西">广西</option>
<option value="湖南">湖南</option>
</select>
<br/>
爱好:
<input type="checkbox" name="hobit" value="篮球"/>篮球
<input type="checkbox" name="hobit" value="足球"/>足球
<input type="checkbox" name="hobit" value="羽毛球"/>羽毛球<br/>
个人简介:
<textarea rows="5" cols="10" name="info"></textarea><br/>
<!-- 隐藏域 -->
<input type="hidden" name="id" value="001"/>
<input type="submit" value="提交"/>
</form>
<hr/>
<h3>POST方式提交</h3>
<form action="/day10/RequestDeom5" method="POST">
用户名:<input type="text" name="name"/><br/>
密码:<input type="password" name="password"/><br/>
性别:
<input type="radio" name="gender" value="男"/>男
<input type="radio" name="gender" value="女"/>女<br/>
籍贯:
<select name="jiguan">
<option value="广东">广东</option>
<option value="广西">广西</option>
<option value="湖南">湖南</option>
</select>
<br/>
爱好:
<input type="checkbox" name="hobit" value="篮球"/>篮球
<input type="checkbox" name="hobit" value="足球"/>足球
<input type="checkbox" name="hobit" value="羽毛球"/>羽毛球<br/>
个人简介:
<textarea rows="5" cols="10" name="info"></textarea><br/>
<!-- 隐藏域 -->
<input type="hidden" name="id" value="001"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
输出: eric=123465 ============================= id=001 jiguan=?????? name=eric gender=??· hobit: ??????,è?????,?????????, password=123465 info=aaaaaa但是存在乱码的问题:
请求参数编码问题 修改POST方式参数编码: request.setCharacterEncoding("utf-8"); 修改GET方式参数编码: 手动解码:String name = new String(name.getBytes("iso-8859-1"),"utf-8");
public class RequestDeom5 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8"); //适用于post
//统一方便的获取请求参数的方法
//根据参数名得到参数值
String name = request.getParameter("name");
String password = request.getParameter("password");
System.out.println(name+"="+password);
System.out.println("=============================");
Enumeration<String> enums = request.getParameterNames();
while( enums.hasMoreElements() ){
String paramName = enums.nextElement();
if("hobit".equals(paramName)) {
System.out.print(paramName+": ");
String[] hobits = request.getParameterValues("hobit");
for(String h: hobits){
System.out.print(h+",");
}
System.out.println();
}
else{
String paramValue = request.getParameter(paramName);
System.out.println(paramName+"="+paramValue);
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("POST方式");
doGet(request,response);
}
}
输出:
POST方式
aaa=11111
=============================
id=001
jiguan=广东
name=aaa
gender=男
hobit: 篮球,足球,羽毛球,
password=11111
info=aaaaa
该方法只能对请求实体内容的数据编码起作用。POST提交的数据在实体内容中,所以该方法对POST方法有效!
GET方法的参数放在URI后面,所以对GET方式无效!!!
所以对于GET只能用于手动解码:String name = new String(name.getBytes("iso-8859-1"),"utf-8");
获取GET方式和Post方式提交的参数:
public class RequestDeom5 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//统一方便的获取请求参数的方法
//根据参数名得到参数值
String name = request.getParameter("name");
if("GET".equals(request.getMethod())){
name = new String(name.getBytes("iso-8859-1"),"utf-8");
}
String password = request.getParameter("password");
if("GET".equals(request.getMethod())){
password = new String(password.getBytes("iso-8859-1"),"utf-8");
}
System.out.println(name+"="+password);
System.out.println("=============================");
Enumeration<String> enums = request.getParameterNames();
while( enums.hasMoreElements() ){
String paramName = enums.nextElement();
if("hobit".equals(paramName)) {
System.out.print(paramName+": ");
String[] hobits = request.getParameterValues("hobit");
for(String h: hobits){
if("GET".equals(request.getMethod())){
h = new String(h.getBytes("iso-8859-1"),"utf-8");
}
System.out.print(h+",");
}
System.out.println();
}
else{
String paramValue = request.getParameter(paramName);
if("GET".equals(request.getMethod())){
paramValue = new String(paramValue.getBytes("iso-8859-1"),"utf-8");
}
System.out.println(paramName+"="+paramValue);
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("POST方式");
doGet(request,response);
}
}
(更改配置文件改编码)(不建议使用) 打来tomcat里面cof文件夹里面的servlet.xml文件更改: <Connector executor="tomcatThreadPool" port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="utf-8"/> 添加:URIEncoding="utf-8" 再重新启动
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>请求参数传递和接收问题</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<body>
<h3>GET方式提交</h3>
<form action="/day10/RequestDeom5" method="GET">
用户名:<input type="text" name="name"/><br/>
密码:<input type="password" name="password"/><br/>
性别:
<input type="radio" name="gender" value="男"/>男
<input type="radio" name="gender" value="女"/>女<br/>
籍贯:
<select name="jiguan">
<option value="广东">广东</option>
<option value="广西">广西</option>
<option value="湖南">湖南</option>
</select>
<br/>
爱好:
<input type="checkbox" name="hobit" value="篮球"/>篮球
<input type="checkbox" name="hobit" value="足球"/>足球
<input type="checkbox" name="hobit" value="羽毛球"/>羽毛球<br/>
个人简介:
<textarea rows="5" cols="10" name="info"></textarea><br/>
<!-- 隐藏域 -->
<input type="hidden" name="id" value="001"/>
<input type="submit" value="提交"/>
</form>
<hr/>
<h3>POST方式提交</h3>
<form action="/day10/RequestDeom5" method="POST">
用户名:<input type="text" name="name"/><br/>
密码:<input type="password" name="password"/><br/>
性别:
<input type="radio" name="gender" value="男"/>男
<input type="radio" name="gender" value="女"/>女<br/>
籍贯:
<select name="jiguan">
<option value="广东">广东</option>
<option value="广西">广西</option>
<option value="湖南">湖南</option>
</select>
<br/>
爱好:
<input type="checkbox" name="hobit" value="篮球"/>篮球
<input type="checkbox" name="hobit" value="足球"/>足球
<input type="checkbox" name="hobit" value="羽毛球"/>羽毛球<br/>
个人简介:
<textarea rows="5" cols="10" name="info"></textarea><br/>
<!-- 隐藏域 -->
<input type="hidden" name="id" value="001"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
判断非法链接:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//得到referer头
String referer = request.getHeader("referer");
System.out.println("referer="+referer);
/**
* 判断非法链接:
* 1)直接访问的话referer=null
* 2)如果当前请求不是来自广告
*/
if(referer==null || !referer.contains("/day10/adv.html")){
response.getWriter().write("当前是非法链接,请回到首页。<a href='/day10/adv.html'>首页</a>");
}else{
//正确的链接
response.getWriter().write("资源正在下载...");
}
}
<body>
广告内容,请猛戳这里。<br/>
<a href="/day10/RespunseDemo2">点击此处下载</a>
</body>
输出:referer=null
referer=http://localhost:8080/day10/adv.html
Http响应
状态码: 服务器处理请求的结果(状态) 常见的状态: 200 : 表示请求处理完成并完美返回 302: 表示请求需要进一步细化。 404: 表示客户访问的资源找不到。 500: 表示服务器的资源发送错误。(服务器内部错误)
常见的响应头: Location: http://www.it315.org/index.jsp -表示重定向的地址,该头和302的状态码一起使用。 Server:apache tomcat ---表示服务器的类型 Content-Encoding: gzip -- 表示服务器发送给浏览器的数据压缩类型 Content-Length: 80 --表示服务器发送给浏览器的数据长度 Content-Language: zh-cn --表示服务器支持的语言 Content-Type: text/html; charset=GB2312 --表示服务器发送给浏览器的数据类型及内容编码 Last-Modified: Tue, 11 Jul 2000 18:23:51 GMT --表示服务器资源的最后修改时间 Refresh: 1;url=http://www.it315.org --表示定时刷新 Content-Disposition: attachment; filename=aaa.zip --表示告诉浏览器以下载方式打开资源(下载文件时用到) Transfer-Encoding: chunked Set-Cookie:SS=Q0=5Lb_nQ; path=/search --表示服务器发送给浏览器的cookie信息(会话管理用到) Expires: -1 --表示通知浏览器不进行缓存 Cache-Control: no-cache Pragma: no-cache Connection: close/Keep-Alive --表示服务器和浏览器的连接状态。close:关闭连接 keep-alive:保存连接
服务器向浏览器发送不同的响应信息,浏览器执行不同的行为 开发者需要设置响应信息通过servlet然后服务器吧信息发送给浏览器 服务器提供了另外一个对象:HttpServletResponse对象,通过servlet改变里面的内容,再把数据发送给浏览器 tomcat服务器把请求信息封装到HttpServletRequest对象,且把响应信息封装到HttpServletResponse 1)tomcat服务器把请求信息封装到HttpServletRequest对象,且把响应信息封装到HttpServletResponse 2)tomcat服务器调用doGet方法,传入request,和response对象 3)通过response对象改变响应信息 4)tomcat服务器把response对象的内容转换成响应格式内容,再发送给浏览器解析。
response.setStatus(404);//修改状态码
response.sendError(404); // 发送404的状态码+404的错误页面
//实体内容(浏览器直接能够看到的内容就是实体内容)
response.getWriter().write("01.hello world"); //字符内容。
response.getOutputStream().write("02.hello world".getBytes());//字节内容
getWriter()和getOutputStream()方法再同一个Response对象中不能同时调用。
因为这两个一个是字节流一个是字符流!!若先使用字节流,那么在客户端则会有对应得编码表来解析出字符,而同时使用字符流就会出现编码表不一致,导致冲突!
请求重定向(Location):302:表示请求需要进一步细化。
需求: 跳转到adv.html
使用请求重定向: 发送一个302状态码+location的响应头
response.setStatus(302);//发送一个302状态码
response.setHeader("location", "/day10/testMehted.html"); //location的响应头
请求重定向简化写法
response.sendRedirect("/day09/adv.html");
定时刷新(refresh) 原理:浏览器认识refresh头,得到refresh头之后重新请求当前资源 response.setHeader("refresh", "1"); //每隔1秒刷新次页面 隔n秒之后跳转另外的资源 response.setHeader("refresh", "3;url=/day09/adv.html");//隔3秒之后跳转到adv.html
content-Type作用 --表示服务器发送给浏览器的数据类型及内容编码
下载图片:
response.setContentType("image/jpg");
response.setHeader("Content-Disposition", "attachment; filename="+file.getName());
FileInputStream in = new FileInputStream(file);
byte[] buf = new byte[1024];
int len = 0;
//把图片内容写出到浏览器
while( (len=in.read(buf))!=-1 ){
response.getOutputStream().write(buf, 0, len);
}
response.setHeader("content-type", "text/html");
response.setContentType("text/html;charset=utf-8");//和上面代码等价。推荐使用此方法
response.setContentType("text/html;charset=utf-8");//发送的类型为html类型,并设置编码格式
response.getWriter().write("<html><head><title>this is tilte</title></head><body>中国</body></html>");
***********添加响应数据编码.png
服务器以utf-8编码 浏览器以utf-8解码
response.getOutputStream().write("<html><head><title>this is tilte</title></head><body>中国</body></html>".getBytes("utf-8"));
字节流不存在编码问题