
正文
创建Cookie,简单模拟登录,记录登录名,购物车记录先前添加内容,session控制登录
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
工作任务:模拟淘宝登录和购物车功能:使用cookie记录登录名,下次登录时能够记得上次的登录名,使用cookie模拟购物车功能,使用session记住登录信息并验证是否登录,防止利用url打开网站,并实现退出登录功能
<%@ 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>Insert title here</title>
</head>
<body>
<%
String username = null;
Cookie[] ck = request.getCookies(); //获取cookie集合
for(Cookie temp:ck){
if(temp.getName().equals("username")){
username = temp.getValue();
}
}
%>
<form action="Check001.jsp" method="post">
卡号:<input type="text" name="username" value="<% if(username != null)out.print(username);%>"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
<%@page import="com.hq.test.CarDao"%>
<%@ 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>Insert title here</title>
</head>
<body>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
if(username == null || password == null || username.equals("") || password.equals("")){
out.write("请正确登录!");
response.setHeader("refresh", "2;url=Login001.jsp");
}else{
//检查登录信息
CarDao cd = new CarDao();
if(cd.checkLogin(username, password)){
out.write("登录成功!");
session.setAttribute("username",username);
session.setMaxInactiveInterval(10);
Cookie ck = new Cookie("username",username);
ck.setMaxAge(10*24*60*60);
response.addCookie(ck);
}else{
out.write("登录失败!");
response.setHeader("refresh", "2;url=Login001.jsp");
}
}
%>
<form action="ShopCar.jsp" method="post">
购物车:<input type="text" name="shop" ><br>
<input type="submit" value="加入购物车">
</form>
</body>
</html>
<%@page import="java.net.URLDecoder"%>
<%@page import="java.net.URLEncoder"%>
<%@ 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>Insert title here</title>
</head>
<body>
<%
String shop =request.getParameter("shop");
String shopcar= null;
Cookie[] cks = request.getCookies(); //获取cookie集合
for(Cookie temp:cks){
if(temp.getName().equals("shop")){
shopcar=URLDecoder.decode(temp.getValue())+" "+shop;
}
}
Cookie ck = new Cookie("shop",URLEncoder.encode(shopcar));
ck.setMaxAge(10*24*60*60);
response.addCookie(ck);
%>
<%=shopcar %>
</body>
</html>







