package ServletPackage;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDemo1 extends HttpServlet {
int i=1;
private static final long serialVersionUID = 4312868947607181532L;
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//threadSafety(response);
//outputHello(response);
//outputChineseByPrintWriter(response);
downloadFileByOutputStream(response);
}
/**
* 下载文件
*/
public void downloadFileByOutputStream(HttpServletResponse response) throws FileNotFoundException, IOException{
//1.获取要下载文件的绝对路径
String realPath = this.getServletContext().getRealPath("/img/timg.jpg");
//2.获得要下载的文件名
String fileName = realPath.substring(realPath.lastIndexOf("\\")+1);
//3.设置Content-disposition响应头控制浏览器以下载的形式打开文件,中文文件名要使用URLEncoder.encode方法进行编码,否则会出现文件名乱码
response.setHeader("content-disposition", "attachment;filename="+fileName);
//response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(fileName, "UTF-8"));
//4.获取要下载的文件输入流
InputStream in = new FileInputStream(realPath);
int len = 0;
//5.创建数据缓冲区
byte[] buffer = new byte[1024];
//6.通过response对象获取OutputStream流
OutputStream out = response.getOutputStream();
//7.将FileInputStream流写入到buffer缓冲区
while ((len = in.read(buffer)) > 0) {
//8.使用OutputStream将缓冲区的数据输出到客户端浏览器
out.write(buffer, 0, len);
}
in.close();
}
/**
* 使用PrintWriter流输出中文
*/
public void outputChineseByPrintWriter(HttpServletResponse response) throws IOException{
String data = "中国";
//通过设置响应头控制浏览器以UTF-8的编码显示数据,如果不加这句话,那么浏览器显示的将是乱码
//response.setHeader("content-type", "text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");//设置将字符以"UTF-8"编码输出到客户端浏览器
PrintWriter out = response.getWriter(); //此必须在设置编码之后
out.write("<meta http-equiv='content-type' content='text/html;charset=UTF-8'/>");//等同于setHeader设置
out.write(data);
//输出数字
/* response.setHeader("content-type", "text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();//获取PrintWriter输出流
out.write("使用PrintWriter流输出数字1:");
out.write(1+"");*/
}
/**
* 使用OutputStream流输出中文
*/
public void outputChineseByOutPutStream(HttpServletResponse response) throws IOException{
String str = "中国";
OutputStream outputStream = response.getOutputStream();
response.setHeader("content-type", "text/html;charset=UTF-8");
byte[] strByteArray = str.getBytes("UTF-8");
outputStream.write(strByteArray);
//输出数字
/* response.setHeader("content-type", "text/html;charset=UTF-8");
OutputStream outputStream = response.getOutputStream();
outputStream.write("使用OutputStream流输出数字1:".getBytes("UTF-8"));
//outputStream.write(1);
outputStream.write((1+"").getBytes());*/
}
/**
* Thread safety test
*/
public void threadSafety(HttpServletResponse response) throws IOException{
response.setHeader("refresh","3;url='http://www.baidu.com'");
response.getWriter().write("gacl");
synchronized (this) {
i++;
try {
Thread.sleep(1000 * 4);
} catch (InterruptedException e) {
e.printStackTrace();
}
response.getWriter().write(i + "");
}
}
/**
* Fistlly Testing
*/
public void outputHello(HttpServletResponse response) throws IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
}
Request类
- setAttribute()在Request域中存储数据
- setCharacterEncoding()设置请求参数的编码方式,只对post请求有效
- getMethod()获取请求类型
- getParameter()获取指定请求参数值
- getParameterNames()获取所有请求参数,返回一个Enumeration枚举类
- getAttribute()获取域中存储的数据
- getAttributeNames()获取域中所有数据,返回一个Enumeration枚举类
- getContextPath()返回当前WEB项目相对路径
- getCookies()获取所有Cookie,返回一个Cookie数组
- getRequestDispatcher()获取转发器,参数路径以/打头,代表WebRoot(当前WEB项目根目录)
- getSession()获取Session对象
Response类
- setContentType()告知浏览器数据类型
- setCharacterEncoding设置Response的编码方式
- setHeader()设置消息头
- setStatus()设置状态吗
- addCookie()添加Cookie
- sendRedirect()重定向
- getOutputStream()获取通向浏览器的字节流(同一次请求处理中,字节流和字符流不能同时存在)
- getWriter()获取通向浏览器的字符流(同一次请求处理中,字节流和字符流不能同时存在)