package com.huawei.response;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author Administrator
* 测试Response
*/
public class TestResponse01 extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 6682298499488718112L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//业务逻辑
//this.testAddOrSetHeader(req, resp);
//this.testWriteSomething(req, resp);
this.testOutputStream(req, resp);
}
protected void testAddOrSetHeader(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
//写一个头信息到 浏览器中
//可以为同一个名字的键添加多个值
resp.addHeader("test-test", "sxt-sxt");
resp.addHeader("test-test", "sxt-sxt1");
//修改同名的值 或是添加头信息
resp.setHeader("cdsxt", "cdsxt");
resp.setHeader("cdsxt", "cdsxt1");
//对setHeader的封装
resp.setDateHeader("now", new Date().getTime());
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
resp.setDateHeader("now", new Date().getTime());
}
protected void testWriteSomething(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
//得到输出器
//告诉浏览器应该怎样去处理当前这一段内容
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
// writer.write("<h1>TestResponse!!!!</h1>");
writer.write("<!DOCTYPE html>");
writer.write("<html>");
writer.write("<head>");
writer.write("<title>Test Response</title>");
writer.write("<script>alert('this is a test response')</script>");
writer.write("</head>");
writer.write("<body>");
if(req.getParameter("name")!=null){
writer.write("<h1 style="color:green;">name have value</h1>");
}else{
writer.write("<h1 style="color:red;">name is null</h1>");
}
writer.write("<img src="1.jpg">");
writer.write("</body>");
writer.write("</html>");
}
/**
* 测试输出流
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void testOutputStream(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
resp.setContentType("image/jpeg");
//文件下载的头
//关于名字乱码的问题 名字的编码格式 只支持一种 ISO8859-1 需要的注意的是 得到字符串byte数组的时候 要指定GBK(兼容IE)编码
resp.setHeader("Content-Disposition", "attachment; filename=""+new String("测试测测侧擦擦大苏打.jpg".getBytes("GBK"),"ISO8859-1")+""");
//得到输出流
OutputStream out = resp.getOutputStream();
//得到文件的输入流
InputStream in = this.getClass().getClassLoader().getResourceAsStream("1.jpg");
byte []bytes = new byte[1024*8];
int len = 0;
while((len = in.read(bytes))!=-1){
out.write(bytes, 0, len);
}
out.flush();
in.close();
out.close();
}
}