首页 > 网站 > WEB开发 > 正文

对Cookie的操作

2024-04-27 15:12:42
字体:
来源:转载
供稿:网友

Servlet端:

package com.Servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@SupPRessWarnings("serial")public class CookieServlet extends HttpServlet {		String getCookie(Cookie[] cookies,String key){		if(cookies!=null){			for(Cookie cookie:cookies){				if(cookie.getName().equals(key))					return cookie.getValue();			}		}		return null;	}	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		Cookie[] cookies=request.getCookies();		String userName=getCookie(cookies,"userName");		String userAge=getCookie(cookies, "userAge");		if(userName==null){			response.addCookie(new Cookie("userName", "Tom"));		}		if(userAge==null){			response.addCookie(new Cookie("userAge", "11"));		}		response.getHeader("Set-Cookie");		response.sendRedirect("Second.jsp");	}}

js写入Cookie:

<script type="text/Javascript">	document.cookie = "userName=Tom11";	document.cookie = "userAge=222";</script>

js读取Cookie:

<script type="text/javascript">	readCookie("userName");		function readCookie(name) {		var cookieValue = "";		var search = name + "=";		if (document.cookie.length > 0) {			offset = document.cookie.indexOf(search);			if (offset != -1) {				offset += search.length;				end = document.cookie.indexOf(";", offset);				if (end == -1)					end = document.cookie.length;				cookieValue = (document.cookie.substring(offset, end))			}		}		alert(cookieValue);	}</script>jsp端读取Cookie:

<%	for (Cookie cookie : request.getCookies()) {		out.println(cookie.getValue());	}%>


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表