发送http头,控制浏览器进制缓存当前文档内容。
只需要在服务器端设置这三项,就可以控制浏览器缓存。
服务器上servlet禁用缓存:
package com.it.servlet.response;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Demo3Servlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setHeader("program", "no-cache");
response.setHeader("cache-control", "no-cache");
response.setDateHeader("expires", -1);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
expires要的是一个时间,用setDateHeader,第二个参数是一个long数据,表示毫秒值,如果没有超过当前时间,则缓存禁用,如果超过当前时间,则在不超过的时间范围内,缓存不禁用,如果超过,缓存禁用。
0代表基准时间1970年1月1日0时0分0秒
-1代表比基准时间小1毫秒
JSP页面禁用缓存:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<!-- 以下三项禁用缓存 -->
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
This is my JSP page. <br>
</body>
</html>
用于显示的都是页面,JSP页面可以通过HTML标记来完成禁用缓存,这个是常用的方法,在页面上通过标记来禁用缓存。
在开发中要想禁用缓存,都是显示页面上操作,也就是JSP上。
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
如果要在servlet上禁用缓存
response.setHeader("program", "no-cache");
response.setHeader("cache-control", "no-cache");
response.setDateHeader("expires", -1);
两种效果是一样的,但是JSP常用。