Cookie的一些操作

package com.email.util;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

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

public final class CookiesUtils {

public static void createCookies(HttpServletResponse reponse,String key,String value,int time,String path){
Cookie cookie = new Cookie(key,value);
cookie.setPath(path);
cookie.setMaxAge(time * 60 *60 * 24);
reponse.addCookie(cookie);
}

/**
*
* @param request
* @param reponse
* @param key
* @param value
* @param time  1  代表1在   7代表一周 30代表一个月
*/
public static void createCookies(HttpServletRequest request,HttpServletResponse reponse,String key,String value,int time){
Cookie cookie = new Cookie(key,value);
cookie.setPath(request.getContextPath()+"/");
cookie.setMaxAge(time * 60 *60 * 24);
reponse.addCookie(cookie);
}

/**
*
* @param request
* @param reponse
* @param key
* @param value
* @param time
* @param chinese  保存中文信息
*/
public static void createCookies(HttpServletRequest request,HttpServletResponse reponse,String key,String value,int time,boolean chinese){

if(key == null || value == null)return;
try {
Cookie cookie = new Cookie(URLEncoder.encode(key, "UTF-8"),URLEncoder.encode(value, "UTF-8"));
cookie.setPath(request.getContextPath()+"/");
cookie.setMaxAge(time * 60 *60 * 24);
reponse.addCookie(cookie);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}


}

public static String getCookiesByKey(HttpServletRequest request,String key,boolean chinese){
if(key == null )return null;
Cookie[] cs = request.getCookies();

try {
if(cs != null){
for(Cookie c : cs){
if(c.getName().equals(URLDecoder.decode(key,"UTF-8"))){
return URLDecoder.decode(c.getValue(),"UTF-8");
}
}

}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

return null;

}
public static String getCookiesByKey(HttpServletRequest request,String key){

Cookie[] cs = request.getCookies();
if(cs != null){
for(Cookie c : cs){
if(c.getName().equals(key)){
return c.getValue();
}
}

}
return null;
}


public static void clear(HttpServletResponse reponse,String key,String path){

Cookie cookie = new Cookie(key,"");
cookie.setPath(path);
cookie.setMaxAge(-1);
reponse.addCookie(cookie);
}

public static void clear(HttpServletRequest request,HttpServletResponse reponse,String key){

Cookie cookie = new Cookie(key,"");
cookie.setPath(request.getContextPath()+"/");
cookie.setMaxAge(-1);
reponse.addCookie(cookie);
}
}

================================================================

你可能感兴趣的:(C++,c,.net,servlet,C#)