Cookie 简单用法

Cookie简单用法

一、用户登录操作


1.首先写一个简单的登录页面,提交到loginServlet

<body>

<formaction="loginServlet">

<tablealign="center">

<tr>

<tdcolspan="2"align="center">

请登录

</td>

</tr>

<tr>

<tdcolspan="1">

用户名:

</td>

<tdcolspan="1">

<inputtype="text"name="userName">

</tr>

<tr>

<tdcolspan="1">

密码:

</td>

<tdcolspan="1">

<inputtype="text"name="password">

</tr>

<tr>

<tdcolspan="2"align="center">

<inputtype="submit"name="submit"value="提交">

</td>

</tr>

</table>

</form>

</body>

2. 新建一个Servlet,取名为loginServlet。在里面创建Cookie,此时为第一次登录,客户端还没有Cookie存在

publicvoiddoGet(HttpServletRequest request, HttpServletResponse response)

throwsServletException, IOException {

StringuserName = request.getParameter("userName"); //接收客户端传过来的值

Stringpassword = request.getParameter("password");

if("xjg".equals(userName)&& "xjg".equals(password)){

//创建用户名Cookie对象

CookiecookieUserName = newCookie("userName",userName);

cookieUserName.setMaxAge(60); //Cookie保存时间

//创建用户密码Cookie对象

CookiecookiePassword = newCookie("password",password);

cookiePassword.setMaxAge(60); //Cookie保存时间

//添加到客户端

response.addCookie(cookieUserName);

response.addCookie(cookiePassword);

request.getSession().setAttribute("userName",userName);

response.sendRedirect("success.jsp");

}else{

response.sendRedirect("fail.jsp");

}

}

二、用户再次登录时操作

   服务器首先读取客户端Cookie信息,如果存在用户名和密码数据,则直接登录,否则显示登录页面。


  1. 在登录页面写上如下代码

<%

//获取客户端Cookie数组

Cookie[]cookies = request.getCookies();

booleanbool = false;

//预定义保存用户名和密码的变量

Stringname = "";

Stringpassword = "";

if(cookies != null)//判断客户端是否存在Cookie对象

{

for(inti = 0; i < cookies.length; i++) {

Cookiecookie = cookies[i];

//判断Cookie的名称是否等于userName

if("userName".equals(cookie.getName())){

name= cookie.getValue();

}

//判断Cookie的名称是否等于password

if("password".equals(cookie.getName())){

password= cookie.getValue();

}

}

//判断用户名和密码是否合法

if("xjg".equals(name)&& "xjg".equals(password)){

bool= true;

}

//判断对客户端的Cookie的操作是否成功,成功则显示登录成功后的页面,

//否则,重定向到登录页面

if(bool) {

response.sendRedirect("success.jsp");

}else{

response.sendRedirect("fail.jsp");

}

}

%>

2.到此,Cookie的创建和读取完毕。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值