HTTP协议:
1. 请求消息:客户端发送给服务器端的数据
* 数据格式:
1. 请求行
2. 请求头
3. 请求空行
4. 请求体
2. 响应消息:服务器端发送给客户端的数据
* 数据格式:
1. 响应行
1. 组成:协议/版本 响应状态码 状态码描述
2. 响应状态码:服务器告诉客户端浏览器本次请求和响应的一个状态。
1. 状态码都是3位数字 :HTTP状态码
2. 分类:
1. 1xx:服务器就收客户端消息,但没有接受完成,等待一段时间后,发送1xx多状态码
2. 2xx:成功。代表:200
3. 3xx:重定向。代表:302(重定向),304(访问缓存)
4. 4xx:客户端错误。
* 代表:
* 404(请求路径没有对应的资源)
* 405:请求方式没有对应的doXxx方法
5. 5xx:服务器端错误。代表:500(服务器内部出现异常)
2. 响应头:
1. 格式:头名称: 值
2. 常见的响应头:
1. Content-Type:服务器告诉客户端本次响应体数据格式以及编码格式
2. Content-disposition:服务器告诉客户端以什么格式打开响应体数据
* 值:
* in-line:默认值,在当前页面内打开
* attachment;filename=xxx:以附件形式打开响应体。文件下载
3. 响应空行
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>
Response对象
* 功能:设置响应消息
1. 设置响应行
1. 格式:HTTP/1.1 200 ok
2. 设置状态码:setStatus(int sc)
2. 设置响应头:setHeader(String name, String value)
3. 设置响应体:
* 使用步骤:
1. 获取输出流
* 字符输出流:PrintWriter getWriter()
* 字节输出流:ServletOutputStream getOutputStream()
2. 使用输出流,将数据输出到客户端浏览器
* 案例:
1. 完成重定向
* 重定向:资源跳转的方式
* 代码实现:
//1. 设置状态码为302
response.setStatus(302);
//2.设置响应头location
response.setHeader("location","/day15/responseDemo2");
重定向到demo2
demo1
/**
* 重定向
*/
@WebServlet("/responseDemo1")
public class ResponseDemo1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("demo1........");
//访问/responseDemo1,会自动跳转到/responseDemo2资源
/* //1. 设置状态码为302
response.setStatus(302);
//2.设置响应头location
response.setHeader("location","/day15/responseDemo2");*/
request.setAttribute("msg","response");
//动态获取虚拟目录
String contextPath = request.getContextPath();
//简单的重定向方法
response.sendRedirect(contextPath+"/responseDemo2");
// response.sendRedirect("http://www.baidu.cn");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
demo2
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("/responseDemo2")
public class ResponseDemo2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("demo2222222........");
Object msg = request.getAttribute("msg");
System.out.println(msg);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
//简单的重定向方法
response.sendRedirect("/day15/responseDemo2");
* 重定向的特点:redirect
1. 地址栏发生变化
2. 重定向可以访问其他站点(服务器)的资源
3. 重定向是两次请求。不能使用request对象来共享数据
* 转发的特点:forward
1. 转发地址栏路径不变
2. 转发只能访问当前服务器下的资源
3. 转发是一次请求,可以使用request对象来共享数据
* forward 和 redirect 区别
forward
demo3转发demo2
@WebServlet("/responseDemo3")
public class ResponseDemo3 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//转发
request.getRequestDispatcher("/responseDemo2").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
* 路径写法:
1. 路径分类
1. 相对路径:通过相对路径不可以确定唯一资源
* 如:./index.html
* 不以/开头,以.开头路径
* 规则:找到当前资源和目标资源之间的相对位置关系
* ./:当前目录
* ../:后退一级目录
2. 绝对路径:通过绝对路径可以确定唯一资源
* 如:http://localhost/day15/responseDemo2 /day15/responseDemo2
* 以/开头的路径
* 规则:判断定义的路径是给谁用的?判断请求将来从哪儿发出
* 给客户端浏览器使用:需要加虚拟目录(项目的访问路径)
* 建议虚拟目录动态获取:request.getContextPath()
* <a> , <form> 重定向...
* 给服务器使用:不需要加虚拟目录
* 转发路径
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>相对路径</h1>
<h1>找到当前资源和目标资源之间的相对位置关系</h1>
<P>
当前资源:location.html
http://localhost/day15/location.html
</P>
<P>
目标资源:
http://localhost/day15/responseDemo2
</P>
<a href="./responseDemo2">
responseDemo2
</a>
<a href="responseDemo2">
responseDemo2
</a>
<br>
<hr>
<h1>绝对路径</h1>
<a href="/day15/responseDemo2">
responseDemo2
</a>
</body>
</html>
2. 服务器输出字符数据到浏览器
* 步骤:
1. 获取字符输出流
2. 输出数据
* 注意:
* 乱码问题:
1. PrintWriter pw = response.getWriter();获取的流的默认编码是ISO-8859-1
2. 设置该流的默认编码:window系统默认GBK(gb2312)
3. 告诉浏览器响应体使用的编码
//简单的形式,设置编码,是在获取流之前设置
response.setContentType("text/html;charset=utf-8");
输出字符流
@WebServlet("/responseDemo4")
public class ResponseDemo4 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取流对象之前,设置流的默认编码:ISO-8859-1 设置为:GBK
// response.setCharacterEncoding("utf-8");
//告诉浏览器,服务器发送的消息体数据的编码。建议浏览器使用该编码解码
//response.setHeader("content-type","text/html;charset=utf-8");
//简单的形式,设置编码
response.setContentType("text/html;charset=utf-8");
//1.获取字符输出流
PrintWriter pw = response.getWriter();
//2.输出数据
//pw.write("<h1>hello response</h1>");
pw.write("<h1>你好啊啊啊 response</h1>");
pw.write("<style>h1{color:red;}</style>");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
3. 服务器输出字节数据到浏览器
* 步骤:
1. 获取字节输出流
2. 输出数据
输出子节流
@WebServlet("/responseDemo5")
public class ResponseDemo5 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//1.获取字节输出流
ServletOutputStream sos = response.getOutputStream();
//2.输出数据
sos.write(getBytes("你好"));
}
public byte[] getBytes(String s) throws UnsupportedEncodingException {
return s.getBytes("utf-8");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
4. 验证码
1. 本质:图片
2. 目的:防止恶意表单注册
验证码html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
/*
分析:
点击超链接或者图片,需要换一张
1.给超链接和图片绑定单击事件
2.重新设置图片的src属性值
*/
window.onload = function(){
//1.获取图片对象
var img = document.getElementById("checkCode");
//2.绑定单击事件
img.onclick = function(){
//加时间戳
var date = new Date().getTime();
img.src = "checkCodeServlet?"+date;
}
}
</script>
</head>
<body>
<img id="checkCode" src="checkCodeServlet" />
<a id="change" href="">看不清换一张?</a>
</body>
</html>
CheckCodeServlet验证码
package cn.itcast.web.servlet;
import org.junit.Test;
import javax.imageio.ImageIO;
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.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Random;
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Random ran = new Random();
int width = 100;
int height = 50;
//1.创建一对象,在内存中图片(验证码图片对象)
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Color colors = new Color(getColor()[0], getColor()[1], getColor()[2]);
Color color = new Color(238, 243, 234);
//2.美化图片
//2.1 填充背景色
Graphics g = image.getGraphics();//画笔对象
// g.setColor(Color.PINK);//设置画笔颜色
//随机生成背景颜色
g.setColor(color);//设置画笔颜色
g.fillRect(0,0,width,height);
//2.2画边框
g.setColor(colors);
g.drawRect(0,0,width-1 ,height-1 );
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
//生成随机角标
for (int i = 1; i <= 4; i++) {
int index = ran.nextInt(str.length());
//获取字符
char ch = str.charAt(index);//随机字符
//2.3写验证码
g.drawString(ch+"",width/5*i,height/2);
}
//2.4画干扰线
g.setColor(colors);
//随机生成坐标点
for (int i = 0; i < 10; i++) {
int x1 = ran.nextInt(width);
int x2 = ran.nextInt(width);
int y1 = ran.nextInt(height);
int y2 = ran.nextInt(height);
g.drawLine(x1,y1,x2,y2);
}
/*
static boolean write (RenderedImage im, String formatName, ImageOutputStream output)
使用支持给定格式的任意 ImageWriter将图像写入 ImageOutputStream 。
*/
//3.将图片输出到页面展示
ImageIO.write(image,"jpg",response.getOutputStream());
}
private Integer[] getColor(){
Integer red = new Random().nextInt(220);
Integer green =new Random().nextInt(220);
Integer blue = new Random().nextInt(220);
Integer[] ColorList = {red,green,blue};
return ColorList;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
CheckCodeServlet验证码2
@WebServlet({"/checkCodeServletTwo"})
public class CheckCodeServletTwo extends HttpServlet {
public CheckCodeServletTwo() {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String uri = request.getRequestURI();
System.out.println("hello : " + uri);
int width = 100;
int height = 50;
String imgType = "gif";
OutputStream output = response.getOutputStream();
String code = CheckCodeServletTwo.GraphicHelper.create(width, height, imgType, output);
System.out.println("验证码内容: " + code);
session.setAttribute(uri, code);
System.out.println(session.getAttribute(uri));
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
public final class GraphicHelper {
public GraphicHelper(CheckCodeServletTwo this$0) {
}
public static String create(int width, int height, String imgType, OutputStream output) {
StringBuffer sb = new StringBuffer();
Random random = new Random();
BufferedImage image = new BufferedImage(width, height, 1);
Graphics graphic = image.getGraphics();
graphic.setColor(Color.getColor("F8F8F8"));
graphic.fillRect(0, 0, width, height);
Color[] colors = new Color[]{Color.BLUE, Color.GRAY, Color.GREEN, Color.RED, Color.BLACK, Color.ORANGE, Color.CYAN};
int i;
int temp;
for(i = 0; i < 50; ++i) {
graphic.setColor(colors[random.nextInt(colors.length)]);
temp = random.nextInt(width);
int y = random.nextInt(height);
int w = random.nextInt(20);
int h = random.nextInt(20);
int signA = random.nextBoolean() ? 1 : -1;
int signB = random.nextBoolean() ? 1 : -1;
graphic.drawLine(temp, y, temp + w * signA, y + h * signB);
}
graphic.setFont(new Font("Comic Sans MS", 1, 30));
for(i = 0; i < 4; ++i) {
temp = random.nextInt(26) + 97;
String s = String.valueOf((char)temp);
sb.append(s);
graphic.setColor(colors[random.nextInt(colors.length)]);
graphic.drawString(s, i * (width / 4), height - height / 2);
}
graphic.dispose();
try {
ImageIO.write(image, imgType, output);
} catch (IOException var16) {
var16.printStackTrace();
}
return sb.toString();
}
}
}
ServletContext对象:
1. 概念:代表整个web应用,可以和程序的容器(服务器)来通信
2. 获取:
1. 通过request对象获取
request.getServletContext();
2. 通过HttpServlet获取
this.getServletContext();
@WebServlet("/servletContextDemo1")
public class ServletContextDemo1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
ServletContext对象获取:
1. 通过request对象获取
request.getServletContext();
2. 通过HttpServlet获取
this.getServletContext();
*/
//1. 通过request对象获取
ServletContext context1 = request.getServletContext();
//2. 通过HttpServlet获取
ServletContext context2 = this.getServletContext();
System.out.println(context1);
System.out.println(context2);
System.out.println(context1 == context2);//true
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
3. 功能:
1. 获取MIME类型:
* MIME类型:在互联网通信过程中定义的一种文件数据类型
* 格式: 大类型/小类型 text/html image/jpeg
* 获取:String getMimeType(String file)
资源文件在E:\apache-tomcat-8.5.84\conf\web.xml上
@WebServlet("/servletContextDemo2")
public class ServletContextDemo2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
ServletContext功能:
1. 获取MIME类型:
* MIME类型:在互联网通信过程中定义的一种文件数据类型
* 格式: 大类型/小类型 text/html image/jpeg
* 获取:String getMimeType(String file)
2. 域对象:共享数据
3. 获取文件的真实(服务器)路径
*/
//2. 通过HttpServlet获取
ServletContext context = this.getServletContext();
//3. 定义文件名称
String filename = "a.jpg";//image/jpeg
//4.获取MIME类型
String mimeType = context.getMimeType(filename);
System.out.println(mimeType);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
2. 域对象:共享数据
1. setAttribute(String name,Object value)
2. getAttribute(String name)
3. removeAttribute(String name)
* ServletContext对象范围:所有用户所有请求的数据
使用需谨慎,所有用户都可以操作,声明周期很长,服务器启动时创建,服务器关闭才销毁.
存储数据多会造成内存压力大
存储数据
@WebServlet("/servletContextDemo3")
public class ServletContextDemo3 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
ServletContext功能:
1. 获取MIME类型:
2. 域对象:共享数据
3. 获取文件的真实(服务器)路径
*/
//2. 通过HttpServlet获取
ServletContext context = this.getServletContext();
//设置数据
context.setAttribute("msg","haha");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
获取存储数据
@WebServlet("/servletContextDemo4")
public class ServletContextDemo4 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
ServletContext功能:
1. 获取MIME类型:
2. 域对象:共享数据
3. 获取文件的真实(服务器)路径
*/
//2. 通过HttpServlet获取
ServletContext context = this.getServletContext();
//获取数据
Object msg = context.getAttribute("msg");
System.out.println(msg);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
3. 获取文件的真实(服务器)路径
1. 方法: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);
@WebServlet("/servletContextDemo5")
public class ServletContextDemo5 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
ServletContext功能:
1. 获取MIME类型:
2. 域对象:共享数据
3. 获取文件的真实(服务器)路径
*/
// 通过HttpServlet获取
ServletContext context = this.getServletContext();
// 获取文件的服务器路径
String b = context.getRealPath("/b.txt");//web目录下资源访问
System.out.println(b);
// File file = new File(realPath);
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);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
案例:
* 文件下载需求:
1. 页面显示超链接
2. 点击超链接后弹出下载提示框
3. 完成图片文件下载
* 分析:
1. 超链接指向的资源如果能够被浏览器解析,则在浏览器中展示,如果不能解析,则弹出下载提示框。不满足需求
2. 任何资源都必须弹出下载提示框
3. 使用响应头设置资源的打开方式:
* content-disposition:attachment;filename=xxx
* 步骤:
1. 定义页面,编辑超链接href属性,指向Servlet,传递资源名称filename
2. 定义Servlet
1. 获取文件名称
2. 使用字节输入流加载文件进内存
3. 指定response的响应头: content-disposition:attachment;filename=xxx
4. 将数据写出到response输出流
html下载页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="/img/九尾.jpg">图片1</a>
<a href="/img/1.avi">视频</a>
<hr>
<a href="/downloadServlet?filename=九尾.jpg">图片1</a>
<a href="/downloadServlet?filename=1.avi">视频</a>
</body>
</html>
DownloadServlet
@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取请求参数,文件名称
String filename = request.getParameter("filename");
System.out.println(filename);
//2.使用字节输入流加载文件进内存
//2.1找到文件服务器路径
ServletContext servletContext = this.getServletContext();
String realPath = servletContext.getRealPath("/img/" + filename);
//2.2用字节流关联
FileInputStream fis = new FileInputStream(realPath);
//3.设置response的响应头
//3.1设置响应头类型:content-type
String mimeType = servletContext.getMimeType(filename);//获取文件的mime类型
response.setHeader("content-type",mimeType);
//3.2设置响应头打开方式:content-disposition
//解决中文文件名问题
//1.获取user-agent请求头、
String agent = request.getHeader("user-agent");
//2.使用工具类方法编码文件名即可
filename = DownLoadUtils.getFileName(agent, filename);
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);
}
}
* 问题:
* 中文文件问题
* 解决思路:
1. 获取客户端使用的浏览器版本信息
2. 根据不同的版本信息,设置filename的编码方式不同
DownLoadUtils工具包
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")) + "?=";
String base64encoded = Base64.getEncoder().encodeToString(filename.getBytes("utf-8"));
filename = "=?utf-8?B?" +base64encoded+ "?=";
System.out.println(base64encoded);
System.out.println(filename);
} else {
// 其它浏览器
filename = URLEncoder.encode(filename, "utf-8");
}
return filename;
}
}