概述
response的API
代码一【请求重定向】
是一种资源跳转方式,可以在服务器之间进行资源跳转
@WebServlet("/servlet/ResponseDemo2")
public class ResponseDemo2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*//设置状态码
response.setStatus(302);
//设置响应头---location(302+location实现请求重定向)
response.setHeader("location","https://www.tmooc.cn/");*/
//请求重定向
response.sendRedirect("https://www.tmooc.cn/");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
代码二【定时刷新】
@WebServlet("/servlet/ResponseDemo1")
public class ResponseDemo1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//解决乱码问题
response.setContentType("text/html;charset=utf8");
//等待提示
response.getWriter().write("恭喜注册成功等待3秒钟跳转到首页!!!");
//定时刷新(时间单位是s)
response.setHeader("refresh","3;url=https://www.tmooc.cn/");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
控制不使用缓存【每次拿到的都是新的东西】
@WebServlet("/servlet/ResponseDemo1")
public class ResponseDemo1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//控制不使用缓存(每次都访问服务器得到新的数据)
/*response.setDateHeader("Expires",-1);
response.setHeader("Cache-control","no-cache");
response.setHeader("pragma","no-cache");*/
//控制使用缓存【使用IE浏览器测试】
response.setDateHeader("Expires",System.currentTimeMillis());
response.setHeader("Cache-control","max-Age=5");//缓存生效时间为5s
//如果不使用缓存,说明每一次时间值都是最新的
Date date=new Date();
String time = date.toLocaleString();
response.getWriter().write(time);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}