前言:前几篇讲解的关于Servlet的入门知识里有关于Response的简单介绍,今天我们就来给Response来个全面的介绍,介绍response的组成部分以及重定向、操作相应体、文件下载、验证码随机生成。
----Response作用----
简单的理解就是往浏览器上写东西。
----组成部分----
响应行 响应头 响应体
----操作响应行----
1、格式:协议/版本 状态码 状态码说明
2、状态码:
1xx:已发送请求
2xx:已完成响应
200:正常响应
3xx:还需浏览器进一步操作
302:重定向 配合响应头:location
304:读缓存
4xx:用户操作错误
404:用户操作错误.
405:访问的方法不存在
5xx:服务器错误
500:内部异常
3、常用方法:setStatus(int 状态码):针对于 1 2 3
了解 :sendError(int 状态码):针对于 4xx和5xx
----操作响应头----
格式:key/value(value可以是多个值)
常用的方法:
1.setHeader(String key,String value):设置字符串形式的响应头
2.了解:setIntHeader(String key,int value):设值整形的响应头
3.了解:setDateHeader(String key,long value):设值时间的响应头
4.addHeader(String key,String value):添加置字符串形式的响应头 之前设置过则追加,若没有设置过则设置
5.了解:addIntHeader(String key,int value):添加整形的响应头
6.了解:addDateHeader(String key,long value):添加时间的响应头
常用的响应头:
1.location:重定向
方式1:
★response.sendRedirect("/day10/loc2");
方式2:
response.setStatus(302);
respooen.setHeader("location","/day10/loc2");
2.refresh:定时刷新
方案1:设置头 refresh
respooen.setHeader("refresh","秒数;url=跳转的路径");
方案2:http的meta标签
3.content-type:设置文件的mime类型,设置响应流的编码及告诉浏览器用什么编码打开
----操作响应体----
常用方法:
Writer getWriter():字符流
ServletOutputStream getOutputStream() :字节流
处理响应中文乱码:
方式1:
response.setContentType("text/html;charset=utf-8");
方式2:理解
response.setHeader("content-type", "text/html;charset=utf-8");
注意:两个流互斥,当响应完成之后,服务器会判断一下流是否已经关闭,若没有关闭,服务器会帮我们关闭.(底层使用的缓冲流)
-----重定向Demo-----
Loc1Servlet.java:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 重定向
*
* @author Fly
*
*/
public class Loc1Servlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("欢迎--->Loc1Servlet");
//方式一
//设置状态码302
// response.setStatus(302);
//设置相应头
// response.setHeader("location", "/Day10/loc2");
//方式二
response.sendRedirect("/Day10/loc2");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
Loc2Servlet.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Loc2Servlet
*/
public class Loc2Servlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Loc2Servlet-->你现在已经到了loc2页面");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
配置文件:
/loc1
/loc2
-----
操作相应体Demo------
PrintSerlvet.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 操作相应体
* @author Fly
*
*/
public class PrintSerlvet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 处理相应中文的乱码
// response.setContentType("text/html;charset=utf-8");
response.setHeader("content-type", "text/html;charset=utf-8");
// ServletOutputStream os = response.getOutputStream();
// 打印表格
// 获取字符流
PrintWriter writer = response.getWriter();
writer.print("");
writer.print("用户名 ");
writer.print("tom ");
writer.print(" 密码 ");
writer.print("123 ");
writer.print("
");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
配置文件:
/print
-----
文件下载Demo-----
使用超链接下载:指定好文件路径即可下载。(注意文件放在WebContent下的download文件夹内)
2、编码下载:
DownloadServlet.java:
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
/**
* 文件下载
*
* @author Fly
*
*/
public class DownloadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取下载文件的名称
String filename = request.getParameter("name");
// 注意中文乱码
filename = new String(filename.getBytes("iso8859-1"), "utf-8");
ServletContext context = this.getServletContext();
// 文件下载
// 1设置文件下载的头信息
String mimeType = context.getMimeType(filename);
response.setContentType(mimeType);
//2.设置下载的头信息
//上午的
//response.setHeader("content-dispostion", "attchment;filename=" + filename);
// 常见的浏览器将文件名称使用utf-8 不推荐 不兼容火狐
// response.setHeader("content-disposition", "attchment;filename="+URLEncoder.encode(filename, "utf-8"));
//方式1:通过的方式 通过工具类编码
//String _filename=DownLoadUtils.getName(request.getHeader("user-agent"), filename);
//response.setHeader("content-disposition", "attachment;filename="+_filename);
//方式2:网络上的方式
response.setHeader("content-disposition", "attachment;filename="+new String(filename.getBytes("gbk"),"iso8859-1"));
//3.对拷流
//获取输入流
InputStream is = context.getResourceAsStream("/download/"+filename);
//获取输出流
ServletOutputStream os = response.getOutputStream();
// int len = -1;
// byte[] b = new byte[1024];
// while ((len=is.read(b)) != -1) {
// os.write(b,0,len);
// }
IOUtils.copy(is, os);//扩展:使用commons-io工具类
os.close();
is.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
配置文件:
/download
浏览器指定路径:(注意文件放在WebContent下的download文件夹内)
CodeServlet.java:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CodeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 使用java图形界面技术绘制一张图片
int charNum = 4;
int width = 30 * 4;
int height = 30;
// 1. 创建一张内存图片
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 2.获得绘图对象
Graphics graphics = bufferedImage.getGraphics();
// 3、绘制背景颜色
graphics.setColor(Color.YELLOW);
graphics.fillRect(0, 0, width, height);
// 4、绘制图片边框
graphics.setColor(Color.BLUE);
graphics.drawRect(0, 0, width - 1, height - 1);
// 5、输出验证码内容
graphics.setColor(Color.RED);
graphics.setFont(new Font("宋体", Font.BOLD, 20));
// 随机输出4个字符
Graphics2D graphics2d = (Graphics2D) graphics;
String s = "ABCDEFGHGKLMNPQRSTUVWXYZ23456789";
Random random = new Random();
// session中要用到
String msg = "";
int x = 5;
for (int i = 0; i < 4; i++) {
int index = random.nextInt(32);
String content = String.valueOf(s.charAt(index));
msg += content;
double theta = random.nextInt(45) * Math.PI / 180;
// 让字体扭曲
graphics2d.rotate(theta, x, 18);
graphics2d.drawString(content, x, 18);
graphics2d.rotate(-theta, x, 18);
x += 30;
}
// 6、绘制干扰线
graphics.setColor(Color.GRAY);
for (int i = 0; i < 5; i++) {
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
graphics.drawLine(x1, y1, x2, y2);
}
// 释放资源
graphics.dispose();
// 图片输出 ImageIO
ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
配置文件:省略。
浏览器:---------完------