Response应用
下载文件
1.创建servlet
public class Response extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1获取要下载的文件的路径
String realPath = "E:\\ideaProjects\\servlet1\\servlet02\\src\\main\\resources\\1.jpg";
//2获取要下载的文件名(截取1.jpg)
String fileName = realPath.substring(realPath.lastIndexOf("\\")+1);
//3设置让浏览器支持下载 //如果文件名为中文,则需改编码
resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));
//4获取下载文件的输入流
FileInputStream fileInputStream = new FileInputStream(realPath);
//5创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
//6获取输出流
ServletOutputStream servletOutputStream = resp.getOutputStream();
//7将输出流写入缓冲区
while ((len=fileInputStream.read(buffer))>0)
{
servletOutputStream.write(buffer,0,len);
}
//关闭输入输出流
fileInputStream.close();
servletOutputStream.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
2.注册servlet……
3.运行
实现验证码
public class Response2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置浏览器2秒刷新一次(**********注意:写在第一行才有效)
resp.setIntHeader("Refresh",2);
//在内存中创建一个图片
BufferedImage image = new BufferedImage(100, 20,BufferedImage.TYPE_INT_RGB);
//创建一个画笔
Graphics2D g = (Graphics2D) image.getGraphics();
//设置图片背景颜色
//设置画笔的颜色
g.setColor(Color.white);
//整个图片填充为白色
g.fillRect(0,0,100,20);
//在图片中画出随机的验证码数据
g.setColor(Color.red);
g.setFont(new Font("Default",1,20));
g.drawString(getNum(),20,20);
//把图片写入浏览器
ImageIO.write(image,"jpg",resp.getOutputStream());
/************************以下是本节学习重点**************************/
//设置类型
resp.setContentType("image/jpeg");
//设置浏览器不缓存
resp.setHeader("Cache-Control","no-cache");
resp.setDateHeader("expires",-1);
resp.setHeader("Pragma","no-cache");
}
//生成随机数
private String getNum(){
Random random = new Random();
String num = random.nextInt(99999)+"";
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < 5-num.length(); i++) {
stringBuffer.append(0);
}
num = stringBuffer.toString() + num;
return num;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
实现重定向
public class Redirect extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/* 等同于:
resp.setHeader("Location","/s3/req2");
resp.setStatus(302);
*/
resp.sendRedirect("/s3/req2");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}