Servlet Cookie & Session

Cookie

  使用Servlet中的Cookie类即可。

  设置cookie

  设置cookie是通过response对象发给客户端。

Cookie cookie_1 = new Cookie("key", "value");
// cookie不设置过期时间(临时cookie),默认在浏览器窗口关闭之前有效。

Cookie cookie_2 = new Cookie("aaa", "bbbbb");

// 设置cookie的过期时间,单位为秒,0表示删除该cookie。
cookie_2.setMaxAge(100);

// 设置域名
cookie_2.setDomain("www.baidu.com");

// 使用setPath(uri), 设定cookie的有效路径,只在指定的path下可见
cookie_2.setPath("/demo/test");

// 将cookie放入response对象中,返回给客户端。
resp.addCookie(cookie_1);
resp.addCookie(cookie_2);

  

  获取cookie

  获取cookie时,是从request对象中获取的。

public class TestgetCookie extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Cookie[] cookies = req.getCookies();
		
		if (cookies != null) {
			for (Cookie c : cookies) {
				System.out.println(c.getName() + "=" + c.getValue());
			}
		}
		
		// 如果要获取某一个cookie对象key对应的value,需要遍历一次Cookie[],封装一下。
		String value = getCookieValue(cookies, "key");
		System.out.println(value);
	}
	
	/**
	 * 获取cookie中某一项的值
	 */
	public static String getCookieValue(Cookie[] cookie, String key) {
		if (cookie != null && key != null) {
			for (Cookie c : cookie) {
				if (c.getName().equals(key)) {
					return c.getValue();
				}
			} 
		} 
		
		return null;
	}
}

  

猜你喜欢

转载自www.cnblogs.com/-beyond/p/10079943.html
今日推荐