首先是一个注册页面:

视图如下:网上蛋糕商城JSP页面

 代码如下:

<!DOCTYPE html>
<html>
<head>
	<title>用户注册</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<link type="text/css" rel="stylesheet" href="css/bootstrap.css">
	<link type="text/css" rel="stylesheet" href="css/style.css">
</head>
<body>
	<!--header-->
	<jsp:include page="header.jsp"/>
	<!--//header-->
	<!--account-->
	<div class="account">
		<div class="container">
			<div class="register">
				<form action="RegisterServlet" method="post">
					<div class="register-top-grid">
						<h3>注册新用户</h3>
						<div class="input">
							<span>用户名 <label style="color:red;">*</label></span>
							<input type="text" name="username" placeholder="请输入用户名" required="required">
						</div>
						<div class="input">
							<span>邮箱 <label style="color:red;">*</label></span>
							<input type="text" name="email" placeholder="请输入邮箱" required="required">
						</div>
						<div class="input">
							<span>密码 <label style="color:red;">*</label></span>
							<input type="password" name="password" placeholder="请输入密码" required="required">
						</div>
						<div class="input">
							<span>收货人<label></label></span>
							<input type="text" name="name" placeholder="请输入收货">
						</div>
						<div class="input">
							<span>收货电话<label></label></span>
							<input type="text" name="phone" placeholder="请输入收货电话">
						</div>
						<div class="input">
							<span>收货地址<label></label></span>
							<input type="text" name="address" placeholder="请输入收货地址">
						</div>
						<div class="clearfix"> </div>
					</div>
					<div class="register-but text-center">
					   <input type="submit" value="提交">
					   <div class="clearfix"> </div>
					</div>
				</form>
				<div class="clearfix"> </div>
			</div>
	    </div>
	</div>
	<!--//account-->
	<!--footer-->
	<jsp:include page="footer.jsp"/>
	<!--//footer-->
</body>
</html>

其中包含头部栏和尾部栏;

头部的代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<div class="header">
    <div class="container">
        <nav class="navbar navbar-default" role="navigation">
            <!--navbar-header-->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav">
                    <li><a href="/index" >首页</a></li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle " data-toggle="dropdown">商品分类
                            <b class="caret"></b>
                        </a>
                        <ul class="dropdown-menu multi-column columns-2">
                            <li>
                                <div class="row">
                                    <div class="col-sm-12">
                                        <h4>商品分类</h4>
                                    </div>
                                </div>
                            </li>
                        </ul>
                    </li>
                    <li><a href="#" >热销</a></li>
                    <li><a href="#" >新品</a></li>
                    <li><a href="register.html" >注册</a></li>
                    <li><a href="#" class="active" >登录</a></li>
                </ul>
                <!--/.navbar-collapse-->
            </div>
            <!--//navbar-header-->
        </nav>
        <div class="header-info">
            <div class="header-right search-box">
                <a href="javascript:;">
                    <span class="glyphicon glyphicon-search" aria-hidden="true"></span>
                </a>
                <div class="search">
                    <form class="navbar-form" action="/">
                        <input type="text" class="form-control" name="keyword">
                        <button type="submit" class="btn btn-default" aria-label="Left Align">
                            搜索
                        </button>
                    </form>
                </div>
            </div>
            <div class="header-right cart">
                <a href="goods_cart.jsp">
                    <span class="glyphicon glyphicon-shopping-cart " aria-hidden="true">
                        <span class="card_num"></span>
                    </span>
                </a>
            </div>
            <div class="clearfix"> </div>
        </div>
        <div class="clearfix"> </div>
    </div>
</div>
<!--//header-->

尾部的代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!--footer-->
<div class="footer">
    <div class="container">
        <div class="text-center">
            <p>www.XXXX.com  </p>
        </div>
    </div>
</div>
<!--//footer-->

(不知道为什么在注册页面不显示头标题,是不是没有把CSS加进去?)

注册完之后点击注册后进入登录界面

登录界面为:网上蛋糕商城JSP页面

 代码为:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<title>用户登录</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<link type="text/css" rel="stylesheet" href="css/bootstrap.css">
	<link type="text/css" rel="stylesheet" href="css/style.css">
</head>
<body>
	<!--header-->
	<jsp:include page="header.jsp"/>
	<!--//header-->
	<!--account-->
	<div class="account">
		<div class="container">
			<div class="register">
				<form action="/JSP/LoginServlet" method="post">
					<div class="register-top-grid">
						<h3>登录页面</h3>
						<div class="input">
							<span>用户名 <label style="color:red;">*</label></span>
							<input type="text" name="username" placeholder="请输入用户名" required="required">
						</div>
						<div class="input">
							<span>密码 <label style="color:red;">*</label></span>
							<input type="password" name="password" placeholder="请输入密码" required="required">
						</div>
						<div class="clearfix"> </div>
					</div>
					<div class="register-but text-center">
					   <input type="submit" value="登录" />
					   <div class="clearfix"> </div>
					</div>
				</form>
				<div class="clearfix"> </div>
			</div>
	    </div>
	</div>
	<!--//account-->
	<!--footer-->
	<jsp:include page="footer.jsp"/>
	<!--//footer-->
</body>
</html>

这个页面用的头部和尾部也是上面的那两个代码;

之后输入用户名和密码,因为没有与数据库连接,此时还只能用自定义一个用户名和密码来进行判断是否正确,正确的话进入购买界面,失败会提醒用户名或者密码错误,会提醒重新登录,如果成功的话会弹出网上蛋糕商城JSP页面

 然后3秒后跳转到网上蛋糕商城JSP页面购买首页,会让选择购买蛋糕还是退出登录,点击购买蛋糕会出现网上蛋糕商城JSP页面,点击购买就会提醒购买了什么蛋糕;

具体代码如下:

蛋糕的一个封装代码:

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<String, Cake> cake = new LinkedHashMap<String, Cake>();
    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<Cake> 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<Cake> 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("对不起!您还没有购买任何商品!<br>"+"<a href='CakeDB.java'>重新购买---</a>"+"<a href='CakeDB.java'>或重新登录</a>");
        } else {
            // 否则显示用户购买蛋糕的信息
            out.write("您购买的蛋糕有:<br>");
            double price = 0;
            for (Cake cake : cart) {
                out.write(cake.getName() + "<br>");
            }
        }
        //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("登录成功,欢迎你!" +"<br/>");
                    response.getWriter().write("您上次访问时间为:"+value+"<br/>");
                    response.getWriter().print("<a href='/JSP/ListCakeServlet'>购买蛋糕</a>"+"<br/>");
                    response.getWriter().print("<a href='/JSP/LogoutServlet'>退出</a>");
                    //设置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("<a href='/JSP/ListCakeServlet'>购买蛋糕</a>"+"<br>");
                response.getWriter().print("<a href='/JSP/LogoutServlet'>退出</a>");
            }
        }
    }
    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<Cake> cakes = CakeDB.getAll();
        out.write("本站提供的蛋糕有:<br>");
        for (Cake cake : cakes) {
            String url = "PurchaseServlet?id=" + cake.getId();
            out.write(cake.getName() + "<a href='" + url
                    + "'>点击购买</a><br>");
        }
    }
}

判断用户输入账户密码是否正确:

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("用户名或密码错误,登录失败,请<a href='/JSP/user.jsp'>重新登录</a>");
        }
	}
	/**
	 * @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<Cake> cart = (List) session.getAttribute("cart");
        if (cart == null) {
            // 首次购买,为用户创建一个购物车(List集合模拟购物车)
            cart = new ArrayList<Cake>();
            // 将购物城存入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

发表回复