一、实验目的
1 、 理解 cookie 在动态网页编程中的作用;
2 、 掌握接收、发送 cookie 的方法;
3 、 通过修改 Cookie 各属性,理解其作用
二、实验内容及步骤
1
、
cookie
基础练习
1 )创建 login.html 页面,包括:
a) 用户名输入;
b) 密码输入;
c) 学号输入;
d) 递交表单后应交由某 servlet 进行处理。
源代码:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
< html >
< head >
< title > login.
html </ title >
< meta http-equiv=
"keywords" content=
"keyword1,keyword2,keyword3">
< meta http-equiv=
"description" content=
"this is my page">
< meta http-equiv=
"content-type" content=
"text/html; charset=UTF-8">
<!--<link
rel="
stylesheet" type="text/
css"
href="./styles.
css">-->
</ head >
< body >
< form action=
"servlet/myServlet" method=
"post">
< table >
< tr >
< td > 学号 </ td >
< td >
< input type=
"text" name=
"sid" size=
"20">
</ td >
</ tr >
< tr >
< td > 用户名 </ td >
< td >
< input type=
"text" name=
"username" size=
"20">
</ td >
</ tr >
< tr >
< td > 密码 </ td >
< td >
< input type=
"password" name=
"password" size=
"20">
</ td >
</ tr >
</ table >
< input name=
"submit" type=
"submit" value=
"
提交
" >
</ form >
</ body >
</ html >
运行结果:
2 )创建 LoginServlet 进行表单处理:
a) 判断 request 对象中是否存在一个名为 “username” 的 cookie ,若不存在,则判断表单中的用户名以及密码是否
为空或为
null ;
i ) 若用户名以及密码
为空或为
null
, 则重定向至 login.html 页面;
ii )否则采用持久性 cookie 保存用户名,采用会话 Cookie 保存学号;
b) 若名为 “username” 的 cookie 存在,则通过 request 获取所有 cookie 的名称和值,并显示在屏幕上。
源代码:
myServlet.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public
class
myServlet
extends HttpServlet {
/**
* Constructor of the object.
*/
public myServlet() {
super ();
}
/**
* Destruction of the
servlet . <br>
*/
public
void destroy() {
super .destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the
servlet . <br>
*
* This method is called when a form has its tag value method equals to get.
*
*
@param request the request send by the client to the server
*
@param response the response send by the server to the client
*
@throws ServletException if an error occurred
*
@throws IOException if an error occurred
*/
|