1.服务器处理请求过程
服务器每接收到一个请求,服务器就会创建一个request对象来封装请求数据,并且服务器也会创建一个response对象,然后服务器传递这2个参数到Servlet的生命周期方法service中,service方法完成参数的强制转换,转换为HttpServletRequest和HttpServletResponse之后,调用非生命周期service方法,在里面获取请求的方法,然后调用doGet或者doPost方法来处理请求,请求处理完成后将处理结果设置到response对象里返回。
2.发送状态码
- sendError(int errorCode)
- sendError(int errorCode,String msg)
- setStatus(int succussCode)
3.响应头相应方法(头就是一个键值对,一个key可以对应一个或者多个value)
- setHeader(String key,String value)
- setIntHeader(“Content-Length”,888)
- setDateHeader(“expires”,-1)
4.重定向(所有请求都得设置location)
public class AServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("AAA");
resp.setStatus(302);
resp.setHeader("location","http://localhost:8080/B");
}
}
public class BServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("BBB");
}
}
5.定时刷新(可以理解为带时间的重定向)
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
writer.print("5秒钟后完成跳转!您看到的一定是乱码!");
resp.setHeader("Refresh","5;URL=http://localhost:8080/B");
}
6.禁用浏览器缓存
- setHeader(“Cache-Control”,“no-cache”);
- setHeader(“pragma”,“no-cache”);
- setIntHeader(“expires”,-1);
7.响应字节数据(用来向客户端发送字节数据)
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String str = "hello";
byte[] bytes = str.getBytes();
resp.getOutputStream().write(bytes);
}