`
jayjayjaylun
  • 浏览: 89777 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

sring WebContentGenerator cache

阅读更多
/*
 * Copyright 2002-2007 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.servlet.support;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.HttpSessionRequiredException;
import org.springframework.web.context.support.WebApplicationObjectSupport;

/**
 * Convenient superclass for any kind of web content generator,
 * like {@link org.springframework.web.servlet.mvc.AbstractController}
 * and {@link org.springframework.web.servlet.mvc.WebContentInterceptor}.
 * Can also be used for custom handlers that have their own
 * {@link org.springframework.web.servlet.HandlerAdapter}.
 *
 * <p>Supports HTTP cache control options. The usage of corresponding
 * HTTP headers can be controlled via the "useExpiresHeader" and
 * "useCacheControlHeader" properties.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @see #setCacheSeconds
 * @see #setRequireSession
 */
public abstract class WebContentGenerator extends WebApplicationObjectSupport {

	/** HTTP method "HEAD" */
	public static final String METHOD_HEAD = "HEAD";

	/** HTTP method "GET" */
	public static final String METHOD_GET = "GET";

	/** HTTP method "POST" */
	public static final String METHOD_POST = "POST";


	private static final String HEADER_PRAGMA = "Pragma";

	private static final String HEADER_EXPIRES = "Expires";

	private static final String HEADER_CACHE_CONTROL = "Cache-Control";


	/** Set of supported methods. HEAD, GET and POST by default. */
	private Set	supportedMethods = new HashSet();

	private boolean requireSession = false;

	/** Use HTTP 1.0 expires header? */
	private boolean useExpiresHeader = true;

	/** Use HTTP 1.1 cache-control header? */
	private boolean useCacheControlHeader = true;

	private int cacheSeconds = -1;


	public WebContentGenerator() {
		this.supportedMethods.add(METHOD_HEAD);
		this.supportedMethods.add(METHOD_GET);
		this.supportedMethods.add(METHOD_POST);
	}


	/**
	 * Set the HTTP methods that this content generator should support.
	 * Default is HEAD, GET and POST.
	 */
	public final void setSupportedMethods(String[] methods) {
		if (ObjectUtils.isEmpty(methods)) {
			throw new IllegalArgumentException("'supportedMethods' must not be empty");
		}
		this.supportedMethods.clear();
		for (int i = 0; i < methods.length; i++) {
			this.supportedMethods.add(methods[i]);
		}
	}

	/**
	 * Return the HTTP methods that this content generator supports.
	 */
	public final String[] getSupportedMethods() {
		return StringUtils.toStringArray(this.supportedMethods);
	}

	/**
	 * Set whether a session should be required to handle requests.
	 */
	public final void setRequireSession(boolean requireSession) {
		this.requireSession = requireSession;
	}

	/**
	 * Return whether a session is required to handle requests.
	 */
	public final boolean isRequireSession() {
		return this.requireSession;
	}

	/**
	 * Set whether to use the HTTP 1.0 expires header. Default is "true".
	 * <p>Note: Cache headers will only get applied if caching is enabled
	 * (or explicitly prevented) for the current request.
	 */
	public final void setUseExpiresHeader(boolean useExpiresHeader) {
		this.useExpiresHeader = useExpiresHeader;
	}

	/**
	 * Return whether the HTTP 1.0 expires header is used.
	 */
	public final boolean isUseExpiresHeader() {
		return this.useExpiresHeader;
	}

	/**
	 * Set whether to use the HTTP 1.1 cache-control header. Default is "true".
	 * <p>Note: Cache headers will only get applied if caching is enabled
	 * (or explicitly prevented) for the current request.
	 */
	public final void setUseCacheControlHeader(boolean useCacheControlHeader) {
		this.useCacheControlHeader = useCacheControlHeader;
	}

	/**
	 * Return whether the HTTP 1.1 cache-control header is used.
	 */
	public final boolean isUseCacheControlHeader() {
		return this.useCacheControlHeader;
	}

	/**
	 * Cache content for the given number of seconds. Default is -1,
	 * indicating no generation of cache-related headers.
	 * <p>Only if this is set to 0 (no cache) or a positive value (cache for
	 * this many seconds) will this class generate cache headers.
	 * <p>The headers can be overwritten by subclasses, before content is generated.
	 */
	public final void setCacheSeconds(int seconds) {
		this.cacheSeconds = seconds;
	}

	/**
	 * Return the number of seconds that content is cached.
	 */
	public final int getCacheSeconds() {
		return this.cacheSeconds;
	}


	/**
	 * Check and prepare the given request and response according to the settings
	 * of this generator. Checks for supported methods and a required session,
	 * and applies the number of cache seconds specified for this generator.
	 * @param request current HTTP request
	 * @param response current HTTP response
	 * @param lastModified if the mapped handler provides Last-Modified support
	 * @throws ServletException if the request cannot be handled because a check failed
	 */
	protected final void checkAndPrepare(
			HttpServletRequest request, HttpServletResponse response, boolean lastModified)
	    throws ServletException {

		checkAndPrepare(request, response, this.cacheSeconds, lastModified);
	}

	/**
	 * Check and prepare the given request and response according to the settings
	 * of this generator. Checks for supported methods and a required session,
	 * and applies the given number of cache seconds.
	 * @param request current HTTP request
	 * @param response current HTTP response
	 * @param cacheSeconds positive number of seconds into the future that the
	 * response should be cacheable for, 0 to prevent caching
	 * @param lastModified if the mapped handler provides Last-Modified support
	 * @throws ServletException if the request cannot be handled because a check failed
	 */
	protected final void checkAndPrepare(
			HttpServletRequest request, HttpServletResponse response, int cacheSeconds, boolean lastModified)
	    throws ServletException {

		// Check whether we should support the request method.
		String method = request.getMethod();
		if (!this.supportedMethods.contains(method)) {
			throw new HttpRequestMethodNotSupportedException(method);
		}

		// Check whether a session is required.
		if (this.requireSession) {
			if (request.getSession(false) == null) {
				throw new HttpSessionRequiredException("Pre-existing session required but none found");
			}
		}

		// Do declarative cache control.
		// Revalidate if the controller supports last-modified.
		applyCacheSeconds(response, cacheSeconds, lastModified);
	}

	/**
	 * Prevent the response from being cached.
	 * See <code>http://www.mnot.net/cache_docs</code>.
	 */
	protected final void preventCaching(HttpServletResponse response) {
		response.setHeader(HEADER_PRAGMA, "No-cache");
		if (this.useExpiresHeader) {
			// HTTP 1.0 header
			response.setDateHeader(HEADER_EXPIRES, 1L);
		}
		if (this.useCacheControlHeader) {
			// HTTP 1.1 header: "no-cache" is the standard value,
			// "no-store" is necessary to prevent caching on FireFox.
			response.setHeader(HEADER_CACHE_CONTROL, "no-cache");
			response.addHeader(HEADER_CACHE_CONTROL, "no-store");
		}
	}

	/**
	 * Set HTTP headers to allow caching for the given number of seconds.
	 * Does not tell the browser to revalidate the resource.
	 * @param response current HTTP response
	 * @param seconds number of seconds into the future that the response
	 * should be cacheable for
	 * @see #cacheForSeconds(javax.servlet.http.HttpServletResponse, int, boolean)
	 */
	protected final void cacheForSeconds(HttpServletResponse response, int seconds) {
		cacheForSeconds(response, seconds, false);
	}

	/**
	 * Set HTTP headers to allow caching for the given number of seconds.
	 * Tells the browser to revalidate the resource if mustRevalidate is
	 * <code>true</code>.
	 * @param response the current HTTP response
	 * @param seconds number of seconds into the future that the response
	 * should be cacheable for
	 * @param mustRevalidate whether the client should revalidate the resource
	 * (typically only necessary for controllers with last-modified support)
	 */
	protected final void cacheForSeconds(HttpServletResponse response, int seconds, boolean mustRevalidate) {
		if (this.useExpiresHeader) {
			// HTTP 1.0 header
			response.setDateHeader(HEADER_EXPIRES, System.currentTimeMillis() + seconds * 1000L);
		}
		if (this.useCacheControlHeader) {
			// HTTP 1.1 header
			String headerValue = "max-age=" + seconds;
			if (mustRevalidate) {
				headerValue += ", must-revalidate";
			}
			response.setHeader(HEADER_CACHE_CONTROL, headerValue);
		}
	}

	/**
	 * Apply the given cache seconds and generate corresponding HTTP headers,
	 * i.e. allow caching for the given number of seconds in case of a positive
	 * value, prevent caching if given a 0 value, do nothing else.
	 * Does not tell the browser to revalidate the resource.
	 * @param response current HTTP response
	 * @param seconds positive number of seconds into the future that the
	 * response should be cacheable for, 0 to prevent caching
	 * @see #cacheForSeconds(javax.servlet.http.HttpServletResponse, int, boolean)
	 */
	protected final void applyCacheSeconds(HttpServletResponse response, int seconds) {
		applyCacheSeconds(response, seconds, false);
	}

	/**
	 * Apply the given cache seconds and generate respective HTTP headers.
	 * <p>That is, allow caching for the given number of seconds in the
	 * case of a positive value, prevent caching if given a 0 value, else
	 * do nothing (i.e. leave caching to the client).
	 * @param response the current HTTP response
	 * @param seconds the (positive) number of seconds into the future that
	 * the response should be cacheable for; 0 to prevent caching; and
	 * a negative value to leave caching to the client.
	 * @param mustRevalidate whether the client should revalidate the resource
	 * (typically only necessary for controllers with last-modified support)
	 */
	protected final void applyCacheSeconds(HttpServletResponse response, int seconds, boolean mustRevalidate) {
		if (seconds > 0) {
			cacheForSeconds(response, seconds, mustRevalidate);
		}
		else if (seconds == 0) {
			preventCaching(response);
		}
		// Leave caching to the client otherwise.
	}

}
分享到:
评论

相关推荐

    spring-cache.xsd+spring-encache.xsd

    标题中的"spring-cache.xsd+spring-encache.xsd"提到了两个XML Schema定义文件,它们是Spring框架中用于缓存管理的配置规范。Spring框架是一个广泛应用的Java企业级应用开发框架,它提供了多种功能,包括但不限于...

    spring-cache(通过key值更新缓存)

    Spring Cache是一个抽象层,它允许开发者在不关注具体缓存实现的情况下,轻松地在应用程序中添加缓存功能。本篇文章将详细探讨如何通过key值更新Spring Cache中的指定缓存,以及相关的缓存管理策略。 首先,让我们...

    spring-cache-4.1.xsd

    spring-cache-4.1.xsd用于spring开发代码提示。用于Java开发。

    springboot 使用spring cache缓存 和 使用fastjson配置redis系列化

    在Spring Boot应用中,Spring Cache是一个强大的工具,用于在应用程序中实现缓存抽象,它可以减少对数据库或远程服务的重复调用,从而提高性能。在本篇文档中,我们将探讨如何使用Spring Cache来缓存数据,并结合...

    spring-cache-4.2.xsd.zip

    标题中的"spring-cache-4.2.xsd.zip"是一个压缩包文件,主要包含了Spring框架缓存模块的相关XML Schema定义文件。这个文件对于理解Spring Cache的配置以及在离线环境中使用Spring框架是至关重要的。 首先,我们需要...

    (SSM框架)memcached整合Spring基于Cache注解.

    在SSM框架中引入Memcached并基于Spring的Cache注解进行整合,可以实现高效、分布式的数据缓存,提升系统性能。下面将详细阐述这一过程中的关键知识点。 1. **Memcached介绍**: Memcached是一款高性能、分布式的...

    jar包-spring-modules-cache.jar

    《深入解析Spring Modules Cache在jar包中的应用》 在Java开发领域,Spring框架以其强大的功能和灵活的扩展性,成为了企业级应用的首选。而Spring Modules Cache是Spring框架的一个扩展,它提供了一种统一的缓存...

    SpringCache与redis集成,优雅的缓存解决方案.docx

    SpringCache与Redis集成,优雅的缓存解决方案 SpringCache是一种基于Java的缓存解决方案,它可以与Redis集成,提供了一种优雅的缓存解决方案。在本文中,我们将对SpringCache与Redis集成的优雅缓存解决方案进行详细...

    springcache+redis springboot maven

    在这个项目中,"springcache+redis"的整合意味着我们要利用Spring Cache的特性,将缓存存储在Redis中,以提升应用的性能。 首先,Spring Cache提供了`@Cacheable`、`@CacheEvict`和`@Caching`等注解,允许我们在...

    spring-cache-mongodb:基于MongoDB的Spring Cache实现

    Spring Cache是Spring框架提供的一种抽象层,允许开发者轻松地在应用程序中引入缓存机制,而无需关心具体的缓存实现。本项目"spring-cache-mongodb"正是一个针对Spring Cache的实现,它利用MongoDB作为底层的存储...

    SSM与memcached整合项目Spring Cache

    在本项目中,我们主要探讨的是如何将Spring Cache与memcached进行整合,以提升应用程序的性能和效率。Spring Cache是Spring框架的一部分,它提供了一种抽象的缓存管理机制,可以方便地集成到各种缓存解决方案中,如...

    Redis整合SpringCache实例

    **Redis整合SpringCache实例** 在现代的Web应用中,数据缓存是提高系统性能的关键技术之一。本示例主要探讨如何将开源的内存数据结构存储系统Redis与Spring Cache框架结合,实现高效的分布式缓存解决方案。Redis以...

    spring-cache

    spring-cache-3.5.0工具包,Java开发一般能用上,缓存工具

    redis-cluster和spring集成,基于cache注解

    综上所述,"redis-cluster和spring集成,基于cache注解" 的项目是一个使用 Spring Cache 集成 Redis 集群的实例,旨在通过注解的方式简化缓存管理,提高应用性能。开发者可以通过导入提供的项目,快速了解和实践这一...

    spring cache + redis 主从

    此外,还需要掌握如何将Spring Cache与Redis整合,以便在应用中高效使用缓存机制。 一、Redis的主从配置 1. 准备工作: - 操作系统要求:Ubuntu 16.04。 - Redis版本:选择适合的稳定版本,例如redis-4.0.9.tar....

    Spring cache

    ### Spring Cache核心知识点 #### 一、Spring Cache简介与特性 Spring Cache 是 Spring 3.1 版本引入的一项重要特性,它不是一种具体的缓存实现(如 EHCache 或 OSCache),而是一种缓存使用的抽象层。通过在现有...

    springboot使用springCache和不使用springCache的对比.zip

    在Spring Boot应用中,Spring Cache是一个强大的功能,它允许我们以声明式的方式管理应用程序的缓存,从而提高性能。Spring Cache抽象了缓存提供者的具体实现,如 EhCache、Redis 或 Hazelcast,使得开发者可以方便...

    springCache

    Spring Cache 是 Spring 框架的一个重要组成部分,它提供了一种在应用程序中统一管理缓存的能力,无需依赖特定的缓存实现,如 Ehcache、Redis 或 Hibernate 二级缓存等。通过 Spring Cache,开发者可以方便地在方法...

    spring-cache-demo-Ruby资源

    spring-cache-demo-Ruby资源

Global site tag (gtag.js) - Google Analytics