Spring mvc 页面缓存设置

使用场景:用在不与数据库交互的页面 但是不会有太大改动页面
web.xml 配置

  
<web-app xmlns="http://java.sun.com/xml/ns/javaee"   
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
                             http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"   
         version="2.5" >

    <display-name>项目名称 webSitedisplay-name>

    <listener> 
     
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>  
    listener>
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>
            WEB-INF/config/applicationContext.xml
        param-value>
    context-param>
    
    <filter>
        <filter-name>PageEhCacheFilterfilter-name>
        
        <filter-class>site.lx.dnf.web.PageEhCacheFilterfilter-class>
        
        <init-param>
            <param-name>patternsparam-name>
            <param-value>Cache.htmlparam-value>
         init-param>
    filter>
    <filter-mapping>
        <filter-name>PageEhCacheFilterfilter-name>
        
        <url-pattern>*.htmlurl-pattern>
    filter-mapping>

web-app>
将经常用到的实体类放到缓存中 

@Entity
@Table(name=”category”)
@Cache(usage= CacheConcurrencyStrategy.READ_WRITE)
public class Category implements Serializable{}


**PageEhCacheFilter class代码**

/***
** 继承net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter 这个类
/
public class PageEhCacheFilter extends SimplePageCachingFilter {


//此处定义为web.xml中filter 下 下patterns中的value值 
    private final static String FILTER_URL_PATTERNS = "patterns";
    private static String[] cacheURLs;
    //继承的方法 dofilter刚开始创建会运行这个方法 
    private void init() throws CacheException {
    // javax.servlet.FilterConfig 的方法
        String patterns = filterConfig.getInitParameter(FILTER_URL_PATTERNS);
        cacheURLs = patterns.split(",");
    }
    //重写dofilter 类 
    @Override
    protected void doFilter(final HttpServletRequest request,final HttpServletResponse response, final FilterChain chain)throws AlreadyGzippedException, AlreadyCommittedException,FilterNonReentrantException, LockTimeoutException, Exception {
    //如果没有缓存 就调用init方法
        if (cacheURLs == null) {
            init();
        }
        //获取请求的地址  
        String url = request.getRequestURI();
        boolean flag = false;
        //如果cacheURLs不为null或者长度大于0  例如:会获取项目下longxin/index.html
        if (cacheURLs != null && cacheURLs.length > 0) {
            for (String cacheURL : cacheURLs) {
            //如果现在的url包含在url数组中 则将flag改为true 在数据库 比如 downloadCache.html  

                if (url.contains(cacheURL.trim())) {
                    flag = true;
                    break;
                }
            }
        }

        // 如果包含我们要缓存的url 就缓存该页面,否则执行正常的页面转向
//获取request里面的参数 
            String query = request.getQueryString();
            //如果参数不为null 
            if (query != null) {
            //在后面加上参数 比如 downLoad.html?param=123
                query = "?" + query;
            }
//            log.info("当前请求被缓存:" + url + query);
            super.doFilter(request, response, chain);
        } else {
            chain.doFilter(request, response);
        }
    }

    private boolean headerContains(final HttpServletRequest request, final String header, final String value) {
        logRequestHeaders(request);
        final Enumeration accepted = request.getHeaders(header);
        while (accepted.hasMoreElements()) {
            final String headerValue = (String) accepted.nextElement();
            if (headerValue.indexOf(value) != -1) {
                return true;
            }
        }
        return false;
    }

    /**
     * @see 
     * 
    使用IE6IE7中都能进行    * net.sf.ehcache.constructs.web.filter.Filter#acceptsGzipEncoding(javax.servlet.http.HttpServletRequest)
     * function: 兼容ie6/7 gzip压缩
     * @author Garmites
     * @createDate 2012-7-4 上午11:07:11
     */
    @Override
    protected boolean acceptsGzipEncoding(HttpServletRequest request) {
        boolean ie6 = headerContains(request, "User-Agent", "MSIE 6.0");
        boolean ie7 = headerContains(request, "User-Agent", "MSIE 7.0");
        return acceptsEncoding(request, "gzip") || ie6 || ie7;
    }
}

ehcache.xml 缓存配置文件

"1.0" encoding="UTF-8"?>


"http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd"
         updateCheck="true" monitoring="autodetect"
         dynamicConfig="true">

    
    "E:\developInstall\tempDataDirectory\longxinjin"/>

    

    class="net.sf.ehcache.transaction.manager.DefaultTransactionManagerLookup"
                              properties="jndiName=java:/TransactionManager" propertySeparator=";"/>


    
    class="" properties=""/>


    
    class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
            properties="peerDiscovery=automatic,
                        multicastGroupAddress=230.0.0.1,
                        multicastGroupPort=4446, timeToLive=1"
            propertySeparator=","
            />


    
    class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"/>

    

    

    
    
    "10000"
            eternal="false"
            timeToIdleSeconds="3600"
            timeToLiveSeconds="3600"
            overflowToDisk="true"
            diskSpoolBufferSizeMB="300"
            maxEntriesLocalDisk="10000000"
            diskPersistent="true"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"
            statistics="false"
            />

    

    
    "
           maxEntriesLocalHeap="10000"
           maxEntriesLocalDisk="1000"
           eternal="false"
           overflowToDisk="true"
           diskSpoolBufferSizeMB="20"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off"
            />


    
    "
           maxEntriesLocalHeap="1000"
           eternal="true"
           overflowToDisk="false"
           memoryStoreEvictionPolicy="FIFO"
            />


    
    "
           maxEntriesLocalHeap="500"
           eternal="false"
           overflowToDisk="true"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           diskPersistent="true"
           diskExpiryThreadIntervalSeconds="1"
           memoryStoreEvictionPolicy="LFU"
            />


    
    "
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="100"
           timeToLiveSeconds="100"
           overflowToDisk="false">

        "/>
        "/>
    


    
    "
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="100"
           timeToLiveSeconds="100"
           overflowToDisk="false">
        "
                properties="replicateAsynchronously=false, replicatePuts=false,
                            replicatePutsViaCopy=false, replicateUpdates=true,
                            replicateUpdatesViaCopy=true, replicateRemovals=false"/>
    

    
    "
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="100"
           timeToLiveSeconds="100"
           overflowToDisk="true">
        "
                properties="asynchronousReplicationIntervalMillis=200"/>
    

    
    

    

    
    
    
    " 
        maxElementsInMemory="1" 
        eternal="false"
        overflowToDisk="false" 
        timeToIdleSeconds="900" 
        timeToLiveSeconds="1800"
        memoryStoreEvictionPolicy="LFU" />

"1.0" encoding="UTF-8" standalone="no"?>
"http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" version="1.7">

    "ehcache">
        
            sequence>
                "1" minOccurs="0" ref="diskStore"/>
                "1" minOccurs="0" ref="sizeOfPolicy"/>
                "1" minOccurs="0" ref="transactionManagerLookup"/>
                "1" minOccurs="0" ref="cacheManagerEventListenerFactory"/>
                "unbounded" minOccurs="0" ref="cacheManagerPeerProviderFactory"/>
                "unbounded" minOccurs="0" ref="cacheManagerPeerListenerFactory"/>
                "1" minOccurs="0" ref="terracottaConfig"/>
                "1" minOccurs="0" ref="defaultCache"/>
                "unbounded" minOccurs="0" ref="cache"/>
            sequence>
            attribute name="name" use="optional"/>
            attribute default="true" name="updateCheck" type="xs:boolean" use="optional"/>
            attribute default="autodetect" name="monitoring" type="monitoringType" use="optional"/>
            attribute default="true" name="dynamicConfig" type="xs:boolean" use="optional"/>
            attribute default="15" name="defaultTransactionTimeoutInSeconds" type="xs:integer" use="optional"/>
            attribute default="0" name="maxBytesLocalHeap" type="memoryUnitOrPercentage" use="optional"/>
            attribute default="0" name="maxBytesLocalOffHeap" type="memoryUnit" use="optional"/>
            attribute default="0" name="maxBytesLocalDisk" type="memoryUnit" use="optional"/>
        
    
    "diskStore">
        
            attribute name="path" use="optional"/>
        
    
    "transactionManagerLookup">
        
            attribute name="class" use="required"/>
            attribute name="properties" use="optional"/>
            attribute name="propertySeparator" use="optional"/>
        
    
    "cacheManagerEventListenerFactory">
        
            attribute name="class" use="required"/>
            attribute name="properties" use="optional"/>
            attribute name="propertySeparator" use="optional"/>
        
    
    "cacheManagerPeerProviderFactory">
        
            attribute name="class" use="required"/>
            attribute name="properties" use="optional"/>
            attribute name="propertySeparator" use="optional"/>
        
    
    "cacheManagerPeerListenerFactory">
        
            attribute name="class" use="required"/>
            attribute name="properties" use="optional"/>
            attribute name="propertySeparator" use="optional"/>
        
    
    "terracottaConfig">
        
            sequence>
                "1" minOccurs="0" name="tc-config">
                    
                        sequence>
                            "unbounded" minOccurs="0" processContents="skip"/>
                        sequence>
                    
                
            sequence>
            attribute default="localhost:9510" name="url" use="optional"/>
            attribute name="rejoin" type="xs:boolean" use="optional" default="false"/>
        
    
    -- add clone support for addition of cacheExceptionHandler. Important! -->
    "defaultCache">
        
            sequence>
                "0" maxOccurs="unbounded" ref="cacheEventListenerFactory"/>
                "0" maxOccurs="unbounded" ref="cacheExtensionFactory"/>
                "0" maxOccurs="unbounded" ref="cacheLoaderFactory"/>
                "0" maxOccurs="unbounded" ref="cacheDecoratorFactory"/>
                "0" maxOccurs="1" ref="bootstrapCacheLoaderFactory"/>
                "0" maxOccurs="1" ref="cacheExceptionHandlerFactory"/>
                "0" maxOccurs="1" ref="pinning"/>
                "0" maxOccurs="1" ref="terracotta"/>
                "0" maxOccurs="1" ref="cacheWriter"/>
                "0" maxOccurs="1" ref="copyStrategy"/>
                "0" maxOccurs="1" ref="elementValueComparator"/>
                "0" maxOccurs="1" ref="sizeOfPolicy"/>
            sequence>
            attribute name="diskExpiryThreadIntervalSeconds" type="xs:integer" use="optional"/>
            attribute name="diskSpoolBufferSizeMB" type="xs:integer" use="optional"/>
            attribute name="diskPersistent" type="xs:boolean" use="optional"/>
            attribute name="diskAccessStripes" type="xs:integer" use="optional" default="1"/>
            attribute name="eternal" type="xs:boolean" use="optional" default="false"/>
            attribute name="maxElementsInMemory" type="xs:integer" use="optional"/>
            attribute name="maxEntriesLocalHeap" type="xs:integer" use="optional"/>
            attribute name="clearOnFlush" type="xs:boolean" use="optional"/>
            attribute name="memoryStoreEvictionPolicy" type="xs:string" use="optional"/>
            attribute name="overflowToDisk" type="xs:boolean" use="optional"/>
            attribute name="timeToIdleSeconds" type="xs:integer" use="optional"/>
            attribute name="timeToLiveSeconds" type="xs:integer" use="optional"/>
            attribute name="maxElementsOnDisk" type="xs:integer" use="optional"/>
            attribute name="maxEntriesLocalDisk" type="xs:integer" use="optional"/>
            attribute name="transactionalMode" type="transactionalMode" use="optional" default="off"/>
            attribute name="statistics" type="xs:boolean" use="optional" default="false"/>
            attribute name="copyOnRead" type="xs:boolean" use="optional" default="false"/>
            attribute name="copyOnWrite" type="xs:boolean" use="optional" default="false"/>
            attribute name="cacheLoaderTimeoutMillis" type="xs:integer" use="optional" default="0"/>
            attribute name="overflowToOffHeap" type="xs:boolean" use="optional" default="false"/>
            attribute name="maxMemoryOffHeap" type="xs:string" use="optional"/>
        
    
    "cache">
        
            sequence>
                "0" maxOccurs="unbounded" ref="cacheEventListenerFactory"/>
                "0" maxOccurs="unbounded" ref="cacheExtensionFactory"/>
                "0" maxOccurs="unbounded" ref="cacheLoaderFactory"/>
                "0" maxOccurs="unbounded" ref="cacheDecoratorFactory"/>
                "0" maxOccurs="1" ref="bootstrapCacheLoaderFactory"/>
                "0" maxOccurs="1" ref="cacheExceptionHandlerFactory"/>
                "0" maxOccurs="1" ref="pinning"/>
                "0" maxOccurs="1" ref="terracotta"/>
                "0" maxOccurs="1" ref="cacheWriter"/>
                "0" maxOccurs="1" ref="copyStrategy"/>
                "0" maxOccurs="1" ref="searchable"/>
                "0" maxOccurs="1" ref="elementValueComparator"/>
                "0" maxOccurs="1" ref="sizeOfPolicy"/>
            sequence>
            attribute name="diskExpiryThreadIntervalSeconds" type="xs:integer" use="optional"/>
            attribute name="diskSpoolBufferSizeMB" type="xs:integer" use="optional"/>
            attribute name="diskPersistent" type="xs:boolean" use="optional"/>
            attribute name="diskAccessStripes" type="xs:integer" use="optional" default="1"/>
            attribute name="eternal" type="xs:boolean" use="optional" default="false"/>
            attribute name="maxElementsInMemory" type="xs:integer" use="optional"/>
            attribute name="maxEntriesLocalHeap" type="xs:integer" use="optional"/>
            attribute name="memoryStoreEvictionPolicy" type="xs:string" use="optional"/>
            attribute name="clearOnFlush" type="xs:boolean" use="optional"/>
            attribute name="name" type="xs:string" use="required"/>
            attribute name="overflowToDisk" type="xs:boolean" use="optional"/>
            attribute name="timeToIdleSeconds" type="xs:integer" use="optional"/>
            attribute name="timeToLiveSeconds" type="xs:integer" use="optional"/>
            attribute name="maxElementsOnDisk" type="xs:integer" use="optional"/>
            attribute name="maxEntriesLocalDisk" type="xs:integer" use="optional"/>
            attribute name="transactionalMode" type="transactionalMode" use="optional" default="off" />
            attribute name="statistics" type="xs:boolean" use="optional" default="false"/>
            attribute name="copyOnRead" type="xs:boolean" use="optional" default="false"/>
            attribute name="copyOnWrite" type="xs:boolean" use="optional" default="false"/>
            attribute name="logging" type="xs:boolean" use="optional" default="false"/>
            attribute name="cacheLoaderTimeoutMillis" type="xs:integer" use="optional" default="0"/>
            attribute name="overflowToOffHeap" type="xs:boolean" use="optional" default="false"/>
            attribute name="maxMemoryOffHeap" type="xs:string" use="optional"/>
            attribute default="0" name="maxBytesLocalHeap" type="memoryUnitOrPercentage" use="optional"/>
            attribute default="0" name="maxBytesLocalOffHeap" type="memoryUnitOrPercentage" use="optional"/>
            attribute default="0" name="maxBytesLocalDisk" type="memoryUnitOrPercentage" use="optional"/>
        
    
    "cacheEventListenerFactory">
        
            attribute name="class" use="required"/>
            attribute name="properties" use="optional"/>
            attribute name="propertySeparator" use="optional"/>
            attribute name="listenFor" use="optional" type="notificationScope" default="all"/>
        
    
    "bootstrapCacheLoaderFactory">
        
            attribute name="class" use="required"/>
            attribute name="properties" use="optional"/>
            attribute name="propertySeparator" use="optional"/>
        
    
    "cacheExtensionFactory">
        
            attribute name="class" use="required"/>
            attribute name="properties" use="optional"/>
            attribute name="propertySeparator" use="optional"/>
        
    
    "cacheExceptionHandlerFactory">
        
            attribute name="class" use="required"/>
            attribute name="properties" use="optional"/>
            attribute name="propertySeparator" use="optional"/>
        
    
    "cacheLoaderFactory">
        
            attribute name="class" use="required"/>
            attribute name="properties" use="optional"/>
            attribute name="propertySeparator" use="optional"/>
        
    
    "cacheDecoratorFactory">
        
            attribute name="class" use="required"/>
            attribute name="properties" use="optional"/>
            attribute name="propertySeparator" use="optional"/>
        
    
    "searchAttribute">
        
            attribute name="name" use="required" type="xs:string"/>
            attribute name="expression" type="xs:string"/>
            attribute name="class" type="xs:string"/>
            attribute name="properties" use="optional"/>
            attribute name="propertySeparator" use="optional"/>
        
    

    "searchable">
      
        sequence>
          "0" maxOccurs="unbounded" ref="searchAttribute"/>
        sequence>
        attribute name="keys" use="optional" type="xs:boolean" default="true"/>
        attribute name="values" use="optional" type="xs:boolean" default="true"/>
      
    

    "pinning">
        
            attribute name="store" use="required" type="pinningStoreType"/>
        
    

    "terracotta">
        
            sequence>
                "0" maxOccurs="1" ref="nonstop"/>
            sequence>
            attribute name="clustered" use="optional" type="xs:boolean" default="true"/>
            attribute name="valueMode" use="optional" type="terracottaCacheValueType" default="serialization"/>
            attribute name="coherentReads" use="optional" type="xs:boolean" default="true"/>
            attribute name="localKeyCache" use="optional" type="xs:boolean" default="false"/>
            attribute name="localKeyCacheSize" use="optional" type="xs:positiveInteger" default="300000"/>
            attribute name="orphanEviction" use="optional" type="xs:boolean" default="true"/>
            attribute name="orphanEvictionPeriod" use="optional" type="xs:positiveInteger" default="4"/>
            attribute name="copyOnRead" use="optional" type="xs:boolean" default="false"/>
            attribute name="coherent" use="optional" type="xs:boolean" default="false"/>
            attribute name="consistency" use="optional" type="consistencyType" default="eventual"/>
            attribute name="synchronousWrites" use="optional" type="xs:boolean" default="false"/>
            attribute name="storageStrategy" use="optional" type="storageStrategyType" default="DCV2"/>
            attribute name="concurrency" use="optional" type="xs:nonNegativeInteger" default="0"/>
            attribute name="localCacheEnabled" use="optional" type="xs:boolean" default="true"/>
            attribute name="compressionEnabled" use="optional" type="xs:boolean" default="false"/>
        
    
    "consistencyType">
        "xs:string">
            "strong" />
            "eventual" />
        
    
    "nonstop">
        
            sequence>
                "0" maxOccurs="1" ref="timeoutBehavior"/>
            sequence>
            attribute name="enabled" use="optional" type="xs:boolean" default="true"/>
            attribute name="immediateTimeout" use="optional" type="xs:boolean" default="false"/>
            attribute name="timeoutMillis" use="optional" type="xs:positiveInteger" default="30000"/>
        
    
    "timeoutBehavior">
        
            attribute name="type" use="optional" type="timeoutBehaviorType" default="exception"/>
            attribute name="properties" use="optional" default=""/>
            attribute name="propertySeparator" use="optional" default=","/>
        
    
    "timeoutBehaviorType">
        "xs:string">
            "noop" />
            "exception" />
            "localReads" />
        
    
    "monitoringType">
        "xs:string">
            "autodetect"/>
            "on"/>
            "off"/>
        
    
    "pinningStoreType">
        "xs:string">
            "localHeap" />
            "localMemory" />
            "inCache" />
        
    
    "terracottaCacheValueType">
        "xs:string">
            "serialization" />
            "identity" />
        
    
    "storageStrategyType">
        "xs:string">
            "classic" />
            "DCV2" />
        
    

    "transactionalMode">
        "xs:string">
            "off"/>
            "xa_strict"/>
            "xa"/>
            "local"/>
        
    

    "cacheWriter">
        
            sequence >
                "0" maxOccurs="1" ref="cacheWriterFactory"/>
            sequence>
            attribute name="writeMode" use="optional" type="writeModeType" default="write-through"/>
            attribute name="notifyListenersOnException" use="optional" type="xs:boolean" default="false"/>
            attribute name="minWriteDelay" use="optional" type="xs:nonNegativeInteger" default="1"/>
            attribute name="maxWriteDelay" use="optional" type="xs:nonNegativeInteger" default="1"/>
            attribute name="rateLimitPerSecond" use="optional" type="xs:nonNegativeInteger" default="0"/>
            attribute name="writeCoalescing" use="optional" type="xs:boolean" default="false"/>
            attribute name="writeBatching" use="optional" type="xs:boolean" default="false"/>
            attribute name="writeBatchSize" use="optional" type="xs:positiveInteger" default="1"/>
            attribute name="retryAttempts" use="optional" type="xs:nonNegativeInteger" default="0"/>
            attribute name="retryAttemptDelaySeconds" use="optional" type="xs:nonNegativeInteger" default="1"/>
            attribute name="writeBehindConcurrency" use="optional" type="xs:nonNegativeInteger" default="1"/>
            attribute name="writeBehindMaxQueueSize" use="optional" type="xs:nonNegativeInteger" default="0"/>
        
    
    "writeModeType">
        "xs:string">
            "write-through" />
            "write-behind" />
        
    
    "cacheWriterFactory">
        
            attribute name="class" use="required"/>
            attribute name="properties" use="optional"/>
            attribute name="propertySeparator" use="optional"/>
        
    

    "copyStrategy">
        
            attribute name="class" use="required" type="xs:string" />
        
    

    "elementValueComparator">
        
            attribute name="class" use="required" type="xs:string" />
        
    

    "sizeOfPolicy">
        
            attribute name="maxDepth" use="required" type="xs:integer" />
            attribute name="maxDepthExceededBehavior" use="optional" default="continue" type="maxDepthExceededBehavior" />
        
    

    "maxDepthExceededBehavior">
        "xs:string">
            "continue"/>
            "abort"/>
        
    

    "notificationScope">
        "xs:string">
            "local"/>
            "remote"/>
            "all"/>
        
    
    "memoryUnit">
        "xs:token">
            "[0-9]+[bBkKmMgG]?"/>
        
    
    "memoryUnitOrPercentage">
        "xs:token">
            "([0-9]+[bBkKmMgG]?|100%|[0-9]{1,2}%)"/>
        
    

你可能感兴趣的:(spring,mvc)