session和cookie的使用
Posted koushr
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了session和cookie的使用相关的知识,希望对你有一定的参考价值。
private String getHeaders(HttpServletRequest request) {
Enumeration en = request.getHeaderNames();
String pasession = "";
while (en.hasMoreElements()) {
String key = en.nextElement().toString();
String value = request.getHeader(key);
if (StringUtils.isNotEmpty(value) && (value.indexOf("PASESSION=") != -1 || value.indexOf("pasession=") != -1)) {
int beginIndex = value.indexOf("PASESSION=");
if (beginIndex < 0) {
beginIndex = value.indexOf("pasession=") + 10;
} else {
beginIndex = beginIndex + 10;
}
String subStr = value.substring(beginIndex);
int endIndex = subStr.indexOf(";");
if (endIndex < 0) {
pasession = subStr;
} else {
pasession = subStr.substring(0, endIndex);
}
break;
}
}
return pasession;
}
private String getPasession(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
String PASESSION = "";
if (null != cookies) {
for (int i = 0; i < cookies.length; i++) {
if ((cookies[i].getName()).equals("PASESSION")) {
PASESSION = cookies[i].getValue();
}
}
}
return PASESSION;
}
public class CookieUtils {
public static Cookie getCookieByName(Cookie[] cookies, String name) {
Map<String, Cookie> cookieMap = ReadCookieMap(cookies);
if (cookieMap.containsKey(name)) {
Cookie cookie = cookieMap.get(name);
return cookie;
} else {
return null;
}
}
/**
* 将cookie封装到Map里面
*
* @return
*/
private static Map<String, Cookie> ReadCookieMap(Cookie[] cookies) {
Map<String, Cookie> cookieMap = new HashMap<>();
if (null != cookies) {
for (Cookie cookie : cookies) {
cookieMap.put(cookie.getName(), cookie);
}
}
return cookieMap;
}
// 创建cookie
public static Cookie createCookie(String cookieName, String cookieValue, int maxAge) {
Cookie cookie = new Cookie(cookieName, cookieValue);
cookie.setMaxAge(maxAge);
cookie.setPath("/");
return cookie;
}
}
以上是关于session和cookie的使用的主要内容,如果未能解决你的问题,请参考以下文章