0
点赞
收藏
分享

微信扫一扫

从Servlet中处理Get重复请求

kiliwalk 2022-04-19 阅读 60
javatomcat

重写getLastModified方法

HttpServlet新定义了service(HttpServletRequest req, HttpServletResponse resp)方法

protected void service(HttpServletRequest req, HttpServletResponse resp) 
    throws ServletException, IOException {
    String method = req.getMethod();
    long lastModified;
    if (method.equals("GET")) {
        lastModified = this.getLastModified(req);
        if (lastModified == -1L) {
            this.doGet(req, resp);
        } else {
            long ifModifiedSince;
            try {
                ifModifiedSince = req.getDateHeader("If-Modified-Since");
            } catch (IllegalArgumentException var9) {
                ifModifiedSince = -1L;
            }

            if (ifModifiedSince < lastModified / 1000L * 1000L) {
                this.maybeSetLastModified(resp, lastModified);
                this.doGet(req, resp);
            } else {
                resp.setStatus(304);
            }
        }
    } else if (method.equals("HEAD")) {
        lastModified = this.getLastModified(req);
        this.maybeSetLastModified(resp, lastModified);
        this.doHead(req, resp);
    } else if (method.equals("POST")) {
        this.doPost(req, resp);
    } else if (method.equals("PUT")) {
        this.doPut(req, resp);
    } 
    // ...
    }

}

其中,在处理get请求中有一个getLastModified方法,默认如下

protected long getLastModified(HttpServletRequest req) {
    return -1L;
}

这个函数返回的是要请求的资源最后一次更改的时间,返回-1也即不支持if-modified-since,这样的话每次请求都会进入doGet方法,可通过继承HttpServlet后重写getLastModified方法达到没有修改时就不进入doGet以节省资源

举报

相关推荐

0 条评论