HTTP缓存 Last-Modified 服务端实现

6 篇文章 0 订阅

 

针对图片资源,根据http协议的缓存机制,进行了服务器更新处理,但遇到了个小问题,一直还没搞清楚的.见代码备注.

 

package com.g3net.servlet;

import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@SuppressWarnings("serial")
public class PicServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		if (!Appcontext.isstarted) {
			return;
		}
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("image/png");
		String key = req.getParameter("k");
		
		long ifModifiedTime = req.getDateHeader("if-modified-since");
		/* 打印输出 浏览器 返回的if-modified-since请求头数据,均返回 1388712683000l,而非 1388712683125l ,省略了毫秒级别数据.*/
		System.out.println("ifModifiedSince:" + ifModifiedTime );
		
		long lastModifyTime = PicCahceUtil.getLastModifyTime(key);
		/* 因此这里根据modifytime进行判断时,应省去毫秒级数据再进行对比*/
		if(ifModifiedTime != -1 && ifModifiedTime != 0 && ifModifiedTime/1000 == lastModifyTime/1000){
			resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
			return;
		}
		byte[] picdata = PicCahceUtil.getPicData(key);
		if (picdata != null && picdata.length > 1) {
			resp.setStatus(HttpServletResponse.SC_OK);
			/*便于测试,下发的"修改时间"为固定值 1388712683125l */
			resp.addDateHeader("Last-Modified", 1388712683125l);
			resp.setHeader("Cache-Control", "max-age=" + 2);//表示浏览器最大缓存两天,两天内会根据modifytime进行更新处理; 超过两天则强制进行更新 
			resp.addDateHeader("Expires", System.currentTimeMillis() + 1000 * 120);//表示浏览器2分钟内不会再次请求服务器,以减少对服务器压力
			/* 下发返回值 */
			OutputStream out = resp.getOutputStream();
			try {
				out.write(picdata);
				out.flush();
			} catch (Exception e) {
				LogService.writeLog(LoggerNameType.FAILLOG, "下发图片数据出错key:"
						+ key, LogService.ERROR);
			} finally {
				out.close();
			}
			// 指标监控
			Appcontext.dataCollection.addFunctionUsingNum("pic", 1);
		} else {
			resp.sendError(HttpServletResponse.SC_NOT_FOUND);
		}
		
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
	
	public static void main(String[] args) {
		long value = 1388712683100l;
		System.out.println(Long.valueOf(value));
	}

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值