JavaWeb笔记8-Cookie应用实例

该实例展示了如何在Java Web应用中通过Cookie来记住用户名,实现登录状态的持久化。在`login.jsp`中,从请求中获取Cookie并设置输入框默认值;在`check.jsp`中,接收用户输入,将用户名保存到Cookie并重定向回登录页面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实例:使用Cookie实现记住用户名

实例代码如下:
a、login.jsp(客户端,负责输入信息)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%!//注意是全局变量符
		String uname;
	%>
	<%
		Cookie[] cookies=request.getCookies();
		for(Cookie cookie:cookies){
			if(cookie.getName().equals("uname")){
				uname=cookie.getValue();
			}
		}
	%>
	<form action="check.jsp" method="post">         <!-- 输出表达式 -->
		用户名:<input type="text" name="uname" value="<%=uname==null?"":uname%>"><br/>
		密码:<input type="password" name="upwd"><br/>
		<input type="submit" value="登录"><br/>
	</form>
</body>
</html>

b、check.jsp(服务端,负责返回带值Cookie)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		request.setCharacterEncoding("UTF-8");
		String uname=request.getParameter("uname");
		String upwd=request.getParameter("upwd");
		//客户端向服务端发出请求,服务端把信息放在Cookie里返回
		//将用户名加入到Cookie中
		//Cookie一般用英文或数字,中文需要编码解码处理
		Cookie cookie=new Cookie("uname",uname);
		
		response.addCookie(cookie);
		//服务端在重定向时响应客户端,同时将Cookie发回客户端
		response.sendRedirect("login.jsp");
	%>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值