JSP复习整理(四)Cookie

一、useCookie.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Using cookie</title>
</head>
<body >
<form action="useCookie.jsp" method="post">
<table border="2"    bgcolor=#E4ECF9>
<tr>
  <td>姓名:</td>
  <td><input type="text" name="name"></td>
 <tr>
    <td>性别:</td>
    <td>女<input type="radio" name="sex" value="F" checked>
                        男<input type="radio" name="sex" value="M"></td>
  </tr>
  <tr>
      <td>喜欢的书:</td>
      <td><select size="2" name="">
         <option selected>none
         <option>《解忧杂货店》
         <option>《白夜行》
         <option>《雪国》
         <option>《*的葬礼》
         </option>
      </select></td>
      <td colspan="2" align="center"><input type="submit" value="发送资料">
      </td>
      </tr>

</table>

</form>
</body>
</html>

二、useCookie.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>use cookie jsp</title>
</head>
<body>
<%
String sname = request.getParameter("name");
String ssex = request.getParameter("sex");
String sbooks = request.getParameter("books");

Cookie nameCookie = new Cookie("name", sname);
Cookie sexCookie = new Cookie("sex", ssex);
Cookie bookCookie = new Cookie("books", sbooks);

response.addCookie(nameCookie);
response.addCookie(sexCookie);
response.addCookie(bookCookie);

response.sendRedirect("responseCookie.jsp");

%>
</body>
</html>

三、responseCookie.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>得到 Cookie中的资料信息</title>
</head>
<body>
<%
Cookie cookies[]=request.getCookies();
int n = cookies.length;
String name="", sex="", articl="";

for(int  i=0; i<n; i++)
	if(cookies[i].getName().equals("name"))
		name=cookies[i].getValue();
	else if(cookies[i].getName().equals("sex"))
		sex=cookies[i].getValue();
	else if(cookies[i].getName().equals("color"))
		color=cookies[i].getValue();

%>
<font color="<%=color%>" size="6"><%=name %></font>
hello。下面就是您的个人资料啦。。
<p>
<%
out.println("性别:<br>");
if(sex.equals("F"))
	out.println("img src='images/g.jpg'>Girl..<p>");
else
	out.println("img src='images/b.jpg'>Boy...<p>");
%>
</body>
</html>

Cookie的一个简单的小例子。。

上一篇:vue学习(五)生命周期 的钩子函数


下一篇:JSP复习整理(二)基本语法