您的位置:首页 > Web前端 > JavaScript

jsp学习--cookie的使用

2017-09-17 16:48 183 查看
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%
//两种创建方式
//	Cookie cookie=new Cookie("uname","ricardo");
Cookie cookie=new Cookie("uname","");
//setValue设置cookie值
cookie.setValue("ricardo");
//setMaxAge设置cookie的有效期
cookie.setMaxAge(50);
//保存到cookie当中
response.addCookie(cookie);
//获取cookie
Cookie[] cookies=request.getCookies();
String uname=null;
if(cookies!=null){
for(int i=0;i<cookies.length;i++){
//getName获取cookie的名称
if("uname".equals(cookies[i].getName())){
//getValue获取cookie的值
uname=cookies[i].getValue();
}
}
}
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'ch07.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>

<body>
<%=uname %>
</body>
</html>


使用cookie存储登录信息的代码实例:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jsp