Import java.io.Serializable;
Import Java.util.HashMap;
Import Java.util.Map;
Import Java.util.UUID;
Import Javax.servlet.http.Cookie;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import org.springframework.beans.factory.annotation.Autowired;
Import com.danga.MemCached.MemCachedClient;
/**
* Remote session is stored in the Memcached cache server session
*/
public class Cachesessionprovider implements sessionprovider{
@Autowired
Private Memcachedclient memcachedclient;
private int expiry = 30;//min
private static final String Jsessionid = "Jsessionid";
Put value
@Override
public void SetAttribute (httpservletrequest request,httpservletresponse response, String name,
Serializable value) {
/* HttpSession session = Request.getsession ();//true Cookie Jsessionid
Session.setattribute (name, value); */
There's a local copy.
Another copy of the memcached
map<string,serializable> session = new hashmap<string,serializable> ();
Session.put (name, value);
Save remote.
Memcachedclient.set (GetSessionID (Request,response), session, EXPIRY*60);
}
Take value
@SuppressWarnings ("Unchecked")
@Override
Public Serializable getattribute (httpservletrequest request,httpservletresponse response, String name) {
map<string,serializable> session = (map<string, serializable>) Memcachedclient.get (getSessionId (Request , response));
if (null! = session) {
return Session.get (name);
}
return null;
}
@Override
public void Logout (httpservletrequest request,httpservletresponse response) {
TODO auto-generated Method Stub
if (Memcachedclient.keyexists (GetSessionID (Request, Response))) {
Memcachedclient.delete (GetSessionID (Request, response));
}
Clean cookies
}
@Override
Public String GetSessionID (httpservletrequest request,httpservletresponse response) {
All the Cookies
cookie[] cookies = request.getcookies ();
if (null! = Cookies && cookies.length > 0) {
for (Cookie c:cookies) {
if (Jsessionid.equals (C.getname ())) {
return C.getvalue ();
}
}
}
Generates a
String sessionId = Uuid.randomuuid (). toString (). ReplaceAll ("-", "");
Cookie cookie = new Cookie (Jsessionid,sessionid);
Cookie.setmaxage (-1);
Cookie.setpath ("/");
Response.addcookie (cookie);
return sessionId;
}
public void Setexpiry (int expiry) {
This.expiry = expiry;
}
}
Note: The usual development time is the local session, on-line after the cache inside, so will httpsession cache cachesession. Spring config file plus <bean id= "Sessionprovider" class= "Cn.itcast.common.web.session.CacheSessionProvider" >
<property name= "expiry" value= "/>"
</bean>
160527, the project on-line after the session (remote session)