HTTP
概念
Hyper Text Transfer Protocol 超文本传输协议
传输协议:定义了客户端和服务器端通信时,发送数据的格式
特点
1. 基于TCP/IP的高级协议
2. 默认端口号:80
3. 基于请求/响应模型:一次请求对应一次响应
4. 无状态的:每次请求之间相互独立,不能交互数据
历史版本
* 1.0:每一次请求响应都会建立新的连接
* 1.1:复用连接
学习HTTP,其实最重要的是学习它的数据格式。
请求消息数据格式
请求消息:客户端发送给服务器端的数据
1. 请求行
格式:请求方式 请求url 请求协议/版本
例子:GET /login.html HTTP/1.1
请求行中的请求方式:HTTP协议有7中请求方式,常用的有2种
- 请求参数在请求行中,在url后
- 请求的url长度有限制的
- 不太安全
- 请求参数在请求体中
- 请求的url长度没有限制的
- 相对安全
2. 请求头
作用:客户端浏览器告诉服务器一些信息
格式:请求头名称: 请求头值
常见的请求头:
3. 请求空行
空行,就是用于分割POST请求的请求头和请求体的。
4. 请求体(正文)
用于封装POST请求消息的请求参数。
以下展示一条请求消息的字符串格式:
POST /login.html HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.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
Referer: http://localhost/login.html
Connection: keep-alive
Upgrade-Insecure-Requests: 1
username=zhangsan
响应消息数据格式.
响应消息:服务器端发送给客户端的数据。
1. 响应行
- 组成:协议/版本 响应状态码 状态码描述
- 响应状态码:服务器告诉客户端浏览器本次请求和响应的一个状态。
状态码都是3位数字 ,分类如下:
1. 1xx:服务器接收客户端消息,但没有接受完成,等待一段时间后,发送1xx状态码
2. 2xx:成功。代表:200
3. 3xx:重定向。代表:302(重定向),304(访问缓存)
4. 4xx:客户端错误。
* 代表:
* 404(请求路径没有对应的资源)
* 405:请求方式没有对应的doXxx方法
5. 5xx:服务器端错误。代表: 500(服务器内部出现异常)
2. 响应头
- 格式-- 头名称: 值
- 常见的响应头:
1. Content-Type:服务器告诉客户端本次响应体数据格式以及编码格式
2. Content-disposition:服务器告诉客户端以什么格式打开响应体数据
* 值:
* in-line:默认值,在当前页面内打开
* attachment;filename=xxx:以附件形式打开响应体。常用于文件下载。
3. 响应空行
4. 响应体
也就是服务器向客户端传输的数据。
响应字符串格式
作为一个简单示例,包含上述的4个部分。
HTTP/1.1 200 OK
Content-Type: text/html;charset=UTF-8
Content-Length: 101
Date: Wed, 06 Jun 2018 07:08:42 GMT
<html>
<head>
<title>$Title$</title>
</head>
<body>
hello , response
</body>
</html>
Request对象
1. request对象和response对象的原理
1. request和response对象是由服务器创建的。我们来使用它们
2. request对象是来获取请求消息,response对象是来设置响应消息
2. request对象继承体系结构:
ServletRequest -- 接口
| 继承
HttpServletRequest -- 接口
| 实现
org.apache.catalina.connector.RequestFacade 类(tomcat)
3. request的功能
3.1. 获取请求消息数据
有三个较为常用的方法已经标红了。
1)获取请求行数据
GET /HttpStudy/demo1?name=zhangsan HTTP/1.1
常用方法在下面列出:
-
获取请求方式 :GET
String getMethod()
-
获取虚拟目录:/HttpStudy
String getContextPath()
-
获取Servlet路径: /demo1
String getServletPath()
-
获取get方式请求参数:name=zhangsan
String getQueryString()
-
获取请求URI: /HttpStudy/demo1
String getRequestURI(): /HttpStudy/demo1
StringBuffer getRequestURL() :http://localhost/HttpStudy/demo1
URI与URL的区别:
URL:统一资源定位符 : http://localhost/HttpStudy/demo1 中华人民共和国
URI:统一资源标识符 : /HttpStudy/demo1 共和国
-
获取协议及版本:HTTP/1.1
String getProtocol()
-
获取客户机的IP地址:
String getRemoteAddr()
实验代码:
package com.zhu.request;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 演示Request对象获取请求行数据
*/
@WebServlet("/requestDemo1")
public class requestDemo1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1. 获取请求方式
String method = request.getMethod();
System.out.println("请求方式"+method);
// 2. (*)获取虚拟目录
String contextPath = request.getContextPath();
System.out.println("虚拟目录:"+contextPath);
// 3. 获取Servlet路径
String servletPath = request.getServletPath();
System.out.println("Servlet路径:"+servletPath);
// 4. 获取get方式请求参数
String queryString = request.getQueryString();
System.out.println("请求参数"+queryString);
// 5. (*)获取请求URI,URL
String requestURI = request.getRequestURI();
StringBuffer requestURL = request.getRequestURL();
System.out.println("URI:"+requestURI);
System.out.println("URL:"+requestURL);
// 6. 获取协议及版本
String prototol = request.getProtocol();
System.out.println("协议及版本:"+prototol);
// 7. 获取客户机的IP地址
String remoteAddr = request.getRemoteAddr();
System.out.println("IP地址:"+remoteAddr);
}
}
结果如下:
2)获取请求头数据
方法:
String getHeader(String name):通过请求头的名称获取请求头的值
Enumeration getHeaderNames():获取所有的请求头名称
3)获取请求体数据
请求体:只有POST请求方式,才有请求体,在请求体中封装了POST请求的请求参数
步骤:
-
获取流对象
- BufferedReader getReader():获取字符输入流,只能操作字符数据
- ServletInputStream getInputStream():获取字节输入流,可以操作所有类型数据
-
再从流对象中拿数据
例子如下:
先在项目中写一个regist.html
然后写一个对应的servlet:
package com.zhu.request;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
@WebServlet("/requestDemo2")
public class requestDemo2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取请求消息体--请求参数
//获取字符流
BufferedReader br = request.getReader();
//读取数据
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
启动tomcat后,访问此资源,输入数据点击注册,观察控制台输出:
可以看到,成功获取到了post请求体中的参数。
3.2.其他功能
在功能1:获取请求消息数据中,只有3个是比较常用的,而下述的功能中,都是较为常用的。
1) 获取请求参数通用方式
不论get还是post请求方式都可以使用下列方法来获取请求参数
- String getParameter(String name):根据参数名称获取参数值 username=zs&password=123
- String[] getParameterValues(String name):根据参数名称获取参数值的数组 hobby=xx&hobby=game(一个参数名称对应多个值的情况)
- Enumeration getParameterNames():获取所有请求的参数名称
- Map<String,String[]> getParameterMap():获取所有参数的map集合
中文乱码问题:请求中的参数是中文或特殊字符,但是获取参数时获取到的是乱码。
* get方式:tomcat 8 已经将get方式乱码问题解决了
* post方式:会乱码
解决:在获取参数前,设置request的编码
request.setCharacterEncoding("utf-8");
2) 请求转发
一种在服务器内部的资源跳转方式。
- 步骤:
- 通过request对象获取请求转发器对象:RequestDispatcher getRequestDispatcher(String path)
- 使用RequestDispatcher对象来进行转发:forward(ServletRequest request, ServletResponse response)
一般写成链式即可,例如:
request.getRequestDispatcher("/requestDemo3").forword(request,response);
- 特点:
- 浏览器地址栏路径不发生变化。
- 只能转发到当前服务器内部资源中。
- 整个转发过程依然还是产生了一次请求。
3) 共享数据
如果一个请求从Servlet_A被转发到了Servlet_B,那么Servlet_B是否可以访问Servlet_A中的数据呢?通过什么方式实现呢?
- 域对象:一个有作用范围的对象,可以在范围内共享数据
- request域:代表一次请求的范围,一般用于请求转发的多个资源中共享数据
- 方法:
- void setAttribute(String name,Object obj):存储数据
- Object getAttitude(String name):通过键获取值
- void removeAttribute(String name):通过键移除键值对
通过以上方法,利用 request域对象,就可以实现共享数据了。
例如在Servlet_A中:
request.setAttribute("msg","hello");
request.getRequestDispatcher("/Servlet_A").forword(request,response);
在Servlet_B中:
Object msg = request.getAttribute("msg");
System.out.println(msg); // hello
4) 获取ServletContext:
ServletContext getServletContext();
ServletContext的作用可移步: ServletConfig、ServletContext的作用
案例:用户登录
通过一个案例演示如何应用Request对象。
案例需求
1.编写login.html登录页面
username & password 两个输入框
2.使用Druid数据库连接池技术,操作mysql,requestTest数据库中user表
3.使用JdbcTemplate技术封装JDBC
4.登录成功跳转到SuccessServlet展示:登录成功!用户名,欢迎您
5.登录失败跳转到FailServlet展示:登录失败,用户名或密码错误
开发步骤
- 创建项目,导入html页面,配置文件,jar包
- 创建数据库环境
CREATE DATABASE requestTest;
USE requestTest;
CREATE TABLE USER(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE NOT NULL,
PASSWORD VARCHAR(32) NOT NULL
);
- 创建包com.zhu.domain,创建类User
package com.zhu.domain;
/**
* 用户的实体类
*/
public class User {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
- 创建包com.zhu.util,编写工具类JDBCUtils
package com.zhu.util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
/**
* JDBC工具类 使用Durid连接池
*/
public class JDBCUtils {
private static DataSource ds ;
static {
try {
//1.加载配置文件
Properties pro = new Properties();
//使用ClassLoader加载配置文件,获取字节输入流
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
//2.初始化连接池对象
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取连接池对象
*/
public static DataSource getDataSource(){
return ds;
}
/**
* 获取连接Connection对象
*/
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
}
- 创建包com.zhu.dao,创建类UserDao,提供login方法
package com.zhu.dao;
import cn.itcast.domain.User;
import cn.itcast.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* 操作数据库中User表的类
*/
public class UserDao {
//声明JDBCTemplate对象共用
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
/**
* 登录方法
* @param loginUser 只有用户名和密码
* @return user包含用户全部数据,没有查询到,返回null
*/
public User login(User loginUser){
try {
//1.编写sql
String sql = "select * from user where username = ? and password = ?";
//2.调用query方法
User user = template.queryForObject(sql,
new BeanPropertyRowMapper<User>(User.class),
loginUser.getUsername(), loginUser.getPassword());
return user;
} catch (DataAccessException e) {
e.printStackTrace();//记录日志
return null;
}
}
}
- 编写com.zhu.web.servlet.LoginServlet类
package com.zhu.web.servlet;
import com.zhu.dao.UserDao;
import com.zhu.domain.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.设置编码
req.setCharacterEncoding("utf-8");
//2.获取请求参数
String username = req.getParameter("username");
String password = req.getParameter("password");
//3.封装user对象
User loginUser = new User();
loginUser.setUsername(username);
loginUser.setPassword(password);
//4.调用UserDao的login方法
UserDao dao = new UserDao();
User user = dao.login(loginUser);
//5.判断user
if (user == null) {
//登录失败
req.getRequestDispatcher("/failServlet").forward(req, resp);
} else {
//登录成功
//存储数据
req.setAttribute("user", user);
//转发
req.getRequestDispatcher("/successServlet").forward(req, resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
- 编写FailServlet和SuccessServlet类
@WebServlet("/successServlet")
public class SuccessServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取request域中共享的user对象
User user = (User) request.getAttribute("user");
if(user != null){
//给页面写一句话
//设置编码
response.setContentType("text/html;charset=utf-8");
//输出
response.getWriter().write("登录成功!"+user.getUsername()+",欢迎您");
}
}
@WebServlet("/failServlet")
public class FailServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//给页面写一句话
//设置编码
response.setContentType("text/html;charset=utf-8");
//输出
response.getWriter().write("登录失败,用户名或密码错误");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
-
login.html中form表单的action路径的写法
* 虚拟目录+Servlet的资源路径
-
BeanUtils工具类,简化数据封装
- setProperty()
- getProperty()
- populate(Object obj , Map map):将map集合的键值对信息,封装到对应的JavaBean对象中
Response对象
功能:设置响应消息
- 设置响应行
- 格式:HTTP/1.1 200 ok
- 设置状态码:setStatus(int sc)
-
设置响应头:setHeader(String name, String value)
-
设置响应体:
* 使用步骤:
1. 获取输出流
* 字符输出流:PrintWriter getWriter()
* 字节输出流:ServletOutputStream getOutputStream()
2. 使用输出流,将数据输出到客户端浏览器
案例
案例1 重定向
重定向是资源跳转的方式,与请求转发的区别总结如下:
序号 |
问题 |
重定向 |
请求转发 |
1 |
第二次请求谁请求的? |
浏览器 |
服务器 |
2 |
浏览器发送了几次请求? |
2次以上 |
1次 |
3 |
servlet可以共享request吗? |
不可以 |
可以 |
4 |
地址栏是否发生改变? |
是 |
不是 |
5 |
浏览器地址栏显示的哪一次访问地址? |
最后一次 |
第一次 |
6 |
可以跳转到什么资源? |
任意资源 |
项目内部 |
7 |
第二次的请求路径是? |
绝对路径 |
内部路径 |
转自JavaWeb 重定向与请求转发的区别和执行流程(图解分析)
代码实现
//1. 设置状态码为302
response.setStatus(302);
//2.设置响应头location
response.setHeader("location","/test/responseDemo2");
简单的重定向方法:
response.sendRedirect("/test/responseDemo2");
相对路径与绝对路径
在web项目中经常会涉及到各种路径,需要明确的是相对路径与绝对路径的区别。
-
相对路径:通过相对路径不可以确定唯一资源,特点是不以/开头,以.开头路径
如:./index.html
./:当前目录
../:后退一级目录
-
绝对路径:通过绝对路径可以确定唯一资源
*如:http://localhost/day15/responseDemo2 /day15/responseDemo2
特点是以/开头的路径。
可以看到绝对路径中也包含了虚拟目录,那么这个虚拟目录何时可以省略不写呢?
判断规则:此路径是给谁用的?-> 判断请求将来从哪儿发出
- 给客户端浏览器使用:需要加虚拟目录(项目的访问路径)
- 建议虚拟目录动态获取而不是写死:request.getContextPath()
- 重定向…
- 给服务器使用:不需要加虚拟目录
案例2 服务器输出字符数据到浏览器
下面用简单的形式在获取流之前设置编码,一行代码完成了上面2和3两个功能,:
response.setContentType("text/html;charset=utf-8");
案例3 服务器输出字节数据到浏览器
- 步骤:
- 获取字节输出流: ServletOutputStream sos = response.getOutputStream;
- 输出数据: sos.write();
ServletContext对象
概念
代表整个web应用,可以和程序的容器(服务器)进行通信。
获取
1. 通过request对象获取
request.getServletContext();
2. 通过HttpServlet获取
this.getServletContext();
功能
1. 获取MIME类型
2. 域对象:共享数据
多个Servlet之间可以通过ServletContext对象实现数据共享。
1. setAttribute(String name,Object value)
2. getAttribute(String name)
3. removeAttribute(String name)
3. 获取文件的真实(服务器)路径
我们知道,当前项目在工作空间中的路径,和发布之后的路径是不一样的,如何获取项目资源在发布后的路径呢?
方法:String getRealPath(String path)
String b = context.getRealPath("/b.txt");//web目录下资源访问
System.out.println(b);
String c = context.getRealPath("/WEB-INF/c.txt");//WEB-INF目录下的资源访问
System.out.println(c);
String a = context.getRealPath("/WEB-INF/classes/a.txt");//src目录下的资源访问
System.out.println(a);
案例:文件下载
- 需求:
- 页面显示超链接
- 点击超链接后弹出下载提示框
- 完成图片文件下载
- 分析:
- 如果超链接直接指向服务器中的图片资源,此资源如果能够被浏览器解析,则在浏览器中展示,如果不能解析,则弹出下载提示框。不满足需求。
- 需求是任何资源都必须弹出下载提示框。
- 使用响应头设置资源的打开方式:
- content-disposition:attachment;filename=xxx
- 步骤:
- 定义页面,编辑超链接href属性,指向Servlet,传递资源名称filename
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="/responseTest/downloadDemo?filename=plane.jpg">图片</a>
</body>
</html>
2. 定义Servlet
- 获取文件名称
- 使用字节输入流加载文件进内存
- 指定response的响应头: content-disposition:attachment;filename=xxx
- 将数据写出到response输出流
package com.zhu;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
@WebServlet("/downloadDemo")
public class downloadDemo extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.获取请求参数:文件名称
String fileName = request.getParameter("filename");
// 2.使用字节输入流加载文件进内存
// 2.1 找到文件服务器路径
ServletContext context = this.getServletContext();
String realPath = context.getRealPath("/img/" + fileName);
// 2.2 用字节流关联
FileInputStream fis = new FileInputStream(realPath);
// 3.设置response响应头
// 3.1 设置响应头类型: content-type
String mimeType = context.getMimeType(fileName); //获取文件的mime类型
response.setHeader("content-type", mimeType);
// 3.2 设置响应头打开方式:content-disposition
response.setHeader("content-disposition", "attachment; filename=" + fileName);
// 4.将输入流的数据写到输出流中
ServletOutputStream sos = response.getOutputStream();
byte[] buff = new byte[1024 * 8];
int len = 0;
while ((len = fis.read(buff)) != -1) {
sos.write(buff, 0, len);
}
fis.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
演示-点击超链接后:
- 问题:
- 中文文件问题
- 解决思路:
- 获取客户端使用的浏览器版本信息
- 根据不同的版本信息,设置filename的编码方式不同
package com.zhu.utils;
import sun.misc.BASE64Encoder;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class DownLoadUtils {
public static String getFileName(String agent, String filename) throws UnsupportedEncodingException {
if (agent.contains("MSIE")) {
// IE浏览器
filename = URLEncoder.encode(filename, "utf-8");
filename = filename.replace("+", " ");
} else if (agent.contains("Firefox")) {
// 火狐浏览器
BASE64Encoder base64Encoder = new BASE64Encoder();
filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
} else {
// 其它浏览器
filename = URLEncoder.encode(filename, "utf-8");
}
return filename;
}
}
在servlet中:
String agent = request.getHeader("user-agent");
filename = DownloadUtils.getFileName(agent,filename);