需要的jar包:
commons-logging-1.0.3.jar
ehcache-core-2.6.9.jar
ehcache-web-2.0.4.jar
log4j-1.2.12.jar
mysql-connector-java-5.1.30.jar
slf4j-api-1.7.2.jar
ehcache.xml 配置文件
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd"> <diskStore path="d:/var/cache/"/> <cache name="SimplePageFragmentCachingFilter" maxElementsInMemory="10" eternal="false" timeToIdleSeconds="10000" //多长时间不访问缓存,就清空缓存 timeToLiveSeconds="20" //缓存生存时间 overflowToDisk="true" memoryStoreEvictionPolicy="LFU"> </cache> </ehcache>
web.xml 配置文件
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>CacheDemo</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>SimplePageFragmentCachingFilter</filter-name> <filter-class>net.sf.ehcache.constructs.web.filter.SimplePageFragmentCachingFilter</filter-class> </filter> <filter-mapping> <filter-name>SimplePageFragmentCachingFilter</filter-name> <url-pattern>*.svl</url-pattern> </filter-mapping> </web-app>
ehcache_index.jsp 文件
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.Date"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function addHtml() {
//alert("run addHtml");
var name = "testCookie";
var cookieVal;
var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg))
cookieVal = unescape(arr[2]);
else
cookieVal = "kongde";
document.getElementById("test").innerHTML="<font>"+cookieVal+"</font>";
if(cookieVal != "kongde") {
document.cookie = name + "="+ (parseInt(cookieVal)+1);
//alert("cookie的值加一");
}
}
</script>
</head>
<body onload="addHtml()">
整个请求链接缓存时间20秒(相当于整个页面缓存时间20秒)<br/><br/>
<%@ include file="head.html" %>
<br/>日期: <%= new Date() %><br/>
<br/><a href="http://www.baidu.com" target="_blank">baidu</a>
</body>
</html>
head.html 文件
<div> I am head ---------- testCookie's value is <span id="test"> </div>
Myservlet.java 文件
package com.demo.cache; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Myservlet */ @WebServlet("/indexservlet.svl") public class Myservlet extends HttpServlet { private static final long serialVersionUID = 1L; private static int count = 0; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("第"+(++count)+"次运行Myservlet"); boolean booleanTemp = true; Cookie[] cookies = request.getCookies(); if(cookies != null) { for(Cookie cookie: cookies) { if("testCookie".equals(cookie.getName())) { booleanTemp = false; break; } } } if(booleanTemp) { System.out.println("添加名为testCookie的cookie"); Cookie cookie = new Cookie("testCookie", "0"); cookie.setPath("/"); response.addCookie(cookie); } DB db = new DB(); ResultSet rs = db.getQuery("select * from user"); try { while(rs.next()) { System.out.println("id: "+rs.getInt("id")+"; name: "+rs.getString("name")); } } catch (SQLException e) { e.printStackTrace(); } finally { db.close(db.getCon(), db.getStmt(), rs); } request.getRequestDispatcher("WEB-INF/ehcache_index.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
DB.java 文件
package com.demo.cache; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DB { private final static String name="root"; private final static String pwd="***"; private Connection con; private Statement stmt; public DB(){ con = null; stmt = null; try{ Class.forName("com.mysql.jdbc.Driver").newInstance(); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8", name, pwd); stmt = con.createStatement(); } catch(Exception e){ e.printStackTrace();; } } public ResultSet getQuery(String queryStr){ ResultSet result = null; try{ System.out.println("对数据库进行访问"); result = stmt.executeQuery(queryStr); }catch(Exception ex){ ex.printStackTrace();; } return result; } public void close(Connection con, Statement stmt, ResultSet rs ) { if(null != con) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } if(null != stmt) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(null != rs) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } System.out.println("关闭数据库连接"); } public Connection getCon() { return con; } public void setCon(Connection con) { this.con = con; } public Statement getStmt() { return stmt; } public void setStmt(Statement stmt) { this.stmt = stmt; } }
项目结构:
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/14055.html