首先是一个注册页面:
代码如下:
用户注册
其中包含头部栏和尾部栏;
头部的代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
尾部的代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
(不知道为什么在注册页面不显示头标题,是不是没有把CSS加进去?)
注册完之后点击注册后进入登录界面
代码为:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
用户登录
这个页面用的头部和尾部也是上面的那两个代码;
之后输入用户名和密码,因为没有与数据库连接,此时还只能用自定义一个用户名和密码来进行判断是否正确,正确的话进入购买界面,失败会提醒用户名或者密码错误,会提醒重新登录,如果成功的话会弹出
然后3秒后跳转到购买首页,会让选择购买蛋糕还是退出登录,点击购买蛋糕会出现,点击购买就会提醒购买了什么蛋糕;
具体代码如下:
蛋糕的一个封装代码:
package test;
public class Cake {
private static final long serialVersionUID = 1L;
private String id;
private String name;
public Cake() {
}
public Cake(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
蛋糕的选择代码:
package test;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
public class CakeDB {
private static Map cake = new LinkedHashMap();
static {
cake.put("1", new Cake("1", "A类蛋糕"));
cake.put("2", new Cake("2", "B类蛋糕"));
cake.put("3", new Cake("3", "C类蛋糕"));
cake.put("4", new Cake("4", "D类蛋糕"));
cake.put("5", new Cake("5", "E类蛋糕"));
}
// 获得所有的蛋糕
public static Collection getAll() {
return cake.values();
}
// 根据指定的id获蛋糕
public static Cake getCake(String id) {
return cake.get(id);
}
}
判断是否购买蛋糕代码:
package test;
import test.Cake;
import javax.servlet.ServletException;
import java.io.*;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet(name = "CartServlet",urlPatterns="/CartServlet")
public class CartServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
// 变量cart引用用户的购物车
List cart = null;
// 变量pruFlag标记用户是否买过商品
boolean purFlag = true;
// 获得用户的session
HttpSession session = req.getSession(false);
// 如果session为null,purFlag置为false
if (session == null) {
purFlag = false;
} else {
// 获得用户购物车
cart = (List) session.getAttribute("cart");
// 如果用的购物车为null,purFlag置为false
if (cart == null) {
purFlag = false;
}
}
/*
* 如果purFlag为false,表明用户没有购买蛋糕 重定向到ListServlet页面
*/
if (!purFlag) {
out.write("对不起!您还没有购买任何商品!
"+"重新购买---"+"或重新登录");
} else {
// 否则显示用户购买蛋糕的信息
out.write("您购买的蛋糕有:
");
double price = 0;
for (Cake cake : cart) {
out.write(cake.getName() + "
");
}
}
//response.sendRedirect("/JSP/LastAccessServlet1")
}
}
显示上一次登录时间:
package test;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet(name = "LastAccessServlet1",urlPatterns = "/LastAccessServlet1")
public class LastAccessServlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException {
//指定服务器输出内容的编码方式UTF-8,防止发生乱码
response.setContentType("text/html;charset=utf-8");
//获取所有cookie
Cookie[] cookies=request.getCookies();
//定义flag的boolean变量,用于判断cookies是否为空
boolean flag=false;
//遍历cookie数组
if(cookies.length >0&&cookies!=null){
for(Cookie cookie:cookies) {
//获取cookie的名称
String name=cookie.getName();
//判断名称是否是lastTime
if("lastTime".equals(name)){
//有该cookie不是第一次访问
flag=true;
//响应数据
//获取cookie的value时间
String value=cookie.getValue();
System.out.println("解码前:"+value);
//URL解码
value= URLDecoder.decode(value, "utf-8");
System.out.println("解码后:"+value);
// response.getWriter().print("登录成功,欢迎你!" +"
");
response.getWriter().write("您上次访问时间为:"+value+"
");
response.getWriter().print("购买蛋糕"+"
");
response.getWriter().print("退出");
//设置cookie的value
//获取当前时间的字符串,重新设置cookie的值,重新发送cookie
Date date=new Date();
SimpleDateFormat timesdf=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str_time=timesdf.format(date);
System.out.println("编码前:"+str_time);
//URL编码
str_time=URLEncoder.encode(str_time, "utf-8");
System.out.println("编码后:"+str_time);
cookie.setValue(str_time);
//设置cookie存活时间
cookie.setMaxAge(60*60*24*30); //一个月
//加入当前cookie请求时间
response.addCookie(cookie);
break;
}
}
//如果cookies中没有时间,也就是没有访问过
if(cookies==null || cookies.length==0 || flag==false){
//设置cookie的value
//获取当前时间的字符串,重新设置cookie的值,重新发送cookie
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str_date=sdf.format(date);
System.out.println("编码前:"+str_date);
//URL编码
str_date= URLEncoder.encode(str_date,"utf-8");
System.out.println("编码后:"+str_date);
Cookie cookie=new Cookie("lastTime",str_date);
//设置cookie存活时间
cookie.setMaxAge(60*60*24*30);//一个月
response.addCookie(cookie);
response.getWriter().print("登录成功,欢迎你" +"!"+"\n");
response.getWriter().write("您好,欢迎您首次访问");
response.getWriter().print("购买蛋糕"+"
");
response.getWriter().print("退出");
}
}
}
public void doPost(HttpServletRequest request,HttpServletResponse
response)throws ServletException,IOException{
this.doPost(request,response);
}
}
购买蛋糕:
package test;
import test.Cake;
import test.CakeDB;
import java.io.*;
import java.util.Collection;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet(name = "ListCakeServlet",urlPatterns="/ListCakeServlet")
public class ListCakeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html; charset=utf-8");
PrintWriter out = resp.getWriter();
Collection cakes = CakeDB.getAll();
out.write("本站提供的蛋糕有:
");
for (Cake cake : cakes) {
String url = "PurchaseServlet?id=" + cake.getId();
out.write(cake.getName() + "点击购买
");
}
}
}
判断用户输入账户密码是否正确:
package test;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import test.User;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
response.setContentType("text/html;charset=utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
PrintWriter pw = response.getWriter();
//假设正确的用户名 是itcast 密码是123
if (("itcast").equals(username) && ("123").equals(password)) {
User user = new User();
user.setUsername(username);
user.setPassword(password);
request.getSession().setAttribute("user", user);
// PrintWriter out = response.getWriter();
pw.write("登录成功,3秒后跳转至LastAccessServlet1中");
response.setHeader("Refresh", "3;URL=/JSP/LastAccessServlet1");
//response.sendRedirect("/JSP/LastAccessServlet1");
//response.sendRedirect("/JSP/ListCakeServlet");
} else {
pw.write("用户名或密码错误,登录失败,请重新登录");
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
退出登录:
package test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LogoutServlet
*/
@WebServlet("/LogoutServlet")
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LogoutServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
// 将Session对象中的User对象移除
request.getSession().removeAttribute("user");
response.sendRedirect("/JSP/user.jsp");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
购物车:
package test;
import test.Cake;
import test.CakeDB;
import java.io.IOException;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet(name = "PurchaseServlet",urlPatterns="/PurchaseServlet")
public class PurchaseServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 获得用户购买的商品
String id = req.getParameter("id");
if (id == null) {
// 如果id为null,重定向到ListBookServlet页面
String url = "CakeDB";
resp.sendRedirect(url);
return;
}
Cake book = CakeDB.getCake(id);
// 创建或者获得用户的Session对象
HttpSession session = req.getSession();
// 从Session对象中获得用户的购物车
List cart = (List) session.getAttribute("cart");
if (cart == null) {
// 首次购买,为用户创建一个购物车(List集合模拟购物车)
cart = new ArrayList();
// 将购物城存入Session对象
session.setAttribute("cart", cart);
}
// 将商品放入购物车
cart.add(book);
// 创建Cookie存放Session的标识号
Cookie cookie = new Cookie("JSESSIONID", session.getId());
cookie.setMaxAge(60 * 30);
cookie.setPath("/Servlet");
resp.addCookie(cookie);
// 重定向到购物车页面
String url = "CartServlet";
resp.sendRedirect(url);
}
}
注册页面的信息保存到本地:
package test;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RegisterServlet
*/
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String USERS = null;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
String username=request.getParameter("username");
String password=request.getParameter("password");
String email=request.getParameter("email");
String name=request.getParameter("name");
String phone=request.getParameter("phone");
String address=request.getParameter("address");
username=new String(username.getBytes("iso8859-1"),"utf-8");
name=new String(name.getBytes("iso8859-1"),"utf-8");
email=new String(email.getBytes("iso8859-1"),"utf-8");
phone=new String(phone.getBytes("iso8859-1"),"utf-8");
address=new String(address.getBytes("iso8859-1"),"utf-8");
System.out.println("用户名:"+username);
System.out.println("密码:"+password);
System.out.println("邮箱:"+email);
System.out.println("收货人:"+name);
System.out.println("电话号:"+phone);
System.out.println("地址:"+address);
response.setContentType("text/html;charset=utf-8");
response.getWriter().println("注册成功!");
createUserData(username, password, email,name,phone,address);
response.sendRedirect("user.jsp");
}
private void createUserData(String username, String password, String email,String name,String phone,String address
) throws IOException {
//String all=name+password+gender+interests;
File userhome = new File("D://" +"USERS" + "/" + username);
userhome.mkdirs();
BufferedWriter writer = new BufferedWriter(new FileWriter(userhome
+ "/profile.txt"));
//writer.write("姓名:"+name + "\t" +"密码:"+ password + "\t" +"性别:"+ gender+"\t"+"兴趣:"+interests);
// writer.write(all);
writer.write("姓名:"+username + "\t" +"密码:"+ password + "\t" +"邮箱:"+ email+"\t"+"收货人:"+name+"\t"+"电话号"+phone+"\t"+"地址:"+address+"\t");
writer.close();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
用户,密码的封装:
package test;
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
以上就是这个注册蛋糕商城的代码;
css获取地址:链接:https://pan.baidu.com/s/1CklDCh581TwdKfY1yL_IbQ
提取码:axd3