javascript.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" isErrorPage="true"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>javascript操作COOKIE</title>
<script type="text/javascript">
function getCookie(name){
var str = document.cookie;
if(!str||str.indexOf(name+"=")<0){
return;
}
var cookies = str.split("; ");
for(var i=0; cookies.length;i++){
cookie = cookies[i];
if(cookie.indexOf(name+"=")==0){
var value = cookie.substring(name.length+1);
return decodeURI(value);
}
}
}
function setCookie(name,value){
document.cookie=name+"="+encodeURI(value);
}
</script>
</head>
<body>
<div align="center" style="margin:10px;">
<fieldset>
<legend>当前有效的Cookie</legend>
<div id="cookieDiv"></div>
<script type="text/javascript">
cookieDiv.innerHTML(document.cookie);
</script>
</fieldset>
<fieldset>
<legend>欢迎您</legend>
<table>
<tr><td>读取Cookie</td>
<td><input name="name1" />
<input type="button" value="读取" onclick="alert(getCookie(name1.value));"/>
</tr>
<tr><td>设置Cookie</td>
<td></td>
</tr>
<tr><td>Name属性:</td>
<td><input name="name2"/></td>
</tr>
<tr><td>Value属性:</td>
<td><input name="value2"/></td>
</tr>
<tr><td></td>
<td><input type="button" value="设置"
onclick="setCookie(name2.value,value2.value);
cookieDiv.innerHTML=document.cookie;"/>
</td>
</tr>
</table>
</fieldset>
</div>
</body>
</html>