jsp和servlet实现购物车
程序员文章站
2022-03-15 09:50:21
...
首先是登录一个简单的表单。
<body>
<head>
<link type="text/css" rel="stylesheet" href="a.css">
<title>购书系统</title>
</head>
<body>
<div class="content">
<h1>购书系统</h1>
<form method="post" action="CheckupServlet">
账户:<input type="text" name="username" class="input-css"/><br/>
密码:<input type="password" name="password" class="input-css"/><br/>
<input type="submit" value="登录" class="btn">
<a href="Register.jsp" >注册</a>
<a href="bookstore.jsp">以游客身份访问</a>
</form>
</div>
</body>
然后提交到CheckupServlet
package la;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
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 javax.servlet.http.HttpSession;
@WebServlet("/CheckupServlet")
public class CheckupServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private Connection conn;
public CheckupServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
public void init() throws ServletException{
super.init();
try{
Class.forName("com.mysql.cj.jdbc.Driver");
}catch (Exception e){
e.printStackTrace();
}
try{
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/U?serverTimezone=UTC","root","123456");
System.out.println("数据库连接成功");
}catch(Exception e){
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String username=request.getParameter("username");
String password=request.getParameter("password");
if(conn!=null)
{
int c=username.length();
int d=password.length();
if(c==0||d==0||username==null||password==null)
{
PrintWriter out=response.getWriter();
out.println("<script>");//输出script标签
out.println("alert('用户或密码不能为空,请重新输入!');");//js语句:输出alert语句
out.println("history.back();");//js语句:输出网页回退语句
//out.print("setTimeout('history.go(-1)', '1000')");
out.println("</script>");//输出script结尾标签
}
else
{java.sql.Statement statement = null;
java.sql.Statement statement1=null;
ResultSet rs = null;
try {
//2. 获取Statement
statement = conn.createStatement();
//3. 准备SQL
String sql = "SELECT username FROM user";
//4. 执行查询,得到ResultSet
rs = ((java.sql.Statement) statement).executeQuery(sql);
boolean flag=false;
while(rs.next())
{
String a=rs.getString("username");
if(a.equals(username))
flag=true;
}
if(flag==false)
{
PrintWriter out=response.getWriter();
out.println("<script>");//输出script标签
out.println("alert('用户名不存在,请重新输入!');");//js语句:输出alert语句
out.println("history.back();");//js语句:输出网页回退语句
//out.print("setTimeout('history.go(-1)', '1000')");
out.println("</script>");//输出script结尾标签
}
} catch (SQLException e) {
e.printStackTrace();
}try
{
statement1=conn.createStatement();
String sql1="select password from user where username='"+username+"'";
rs = ((java.sql.Statement) statement1).executeQuery(sql1);
while(rs.next())
{
String b=rs.getString(1);
System.out.println("b="+b);
if(b.equals(password)!=true)
{
PrintWriter out=response.getWriter();
out.println("<script>");//输出script标签
out.println("alert('密码不正确,请重新输入!');");//js语句:输出alert语句
out.println("history.back();");//js语句:输出网页回退语句
//out.print("setTimeout('history.go(-1)', '1000')");
out.println("</script>");//输出script结尾标签
}
else
{
PrintWriter out=response.getWriter();
out.println("登录成功,2秒后自动跳转<br>");
response.setHeader("Refresh","3,url=bookstore.jsp");
HttpSession session=request.getSession();
session.setAttribute("user", username);
out.print("如果没有跳转,请点击<br>");
out.print("<a href='bookstore.jsp'>这里</a>");
}
}
}catch (SQLException e) {
e.printStackTrace();
}
}
}
else{
response.sendError(500,"数据库连接出错!");
}
}
}
bookstore主界面
<body>
<head>
<link type="text/css" rel="stylesheet" href="a.css">
<title>购书系统 - 购书</title>
</head>
<body>
<div class="content">
<h1>购书系统 - 购书</h1>
</div>
<% if(session.getAttribute("user")!=null)
{ %>
<h4 class="ys1">欢迎<%=session.getAttribute("user") %></h4>
<a class="ys1" href="Logout.jsp">注销.</a>
<a class="ys2" href="alterpassword.jsp" >修改密码</a>
<a class="ys2" href="showCar.jsp">查看购物车</a>
<%
}else {
%>
<a class="ys1"href="login.jsp">去登录</a>
<a class="ys2"href="Register.jsp">去注册</a>
<%} %>
<form action="bookstore.jsp" method="post">
<input type="text" class="ys1" name="select">
<input type="submit" value="按照分类搜索" >
</form>
<form action="bookstore.jsp" method="post">
<input type="text" class="ys1" name="bookname">
<input type="submit" value="按照书名搜索" >
</form>
<form action="bookstore.jsp" method="post">
<input type="text" name="price1" class="ys1">~
<input type="text" name="price2" >
<input type="submit" value="按照价格区间搜索" >
</form>
<table class="ys5" border="4" >
<tr>
<td align="center">书号</td>
<td align="center">书名</td>
<td align="center">价格</td>
<td align="center">作者</td>
<td align="center">所属分类</td>
<td align="center">购买</td>
</tr>
<%Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/U?serverTimezone=UTC","root","123456");
Statement stmt = connect.createStatement();
String sort=request.getParameter("select");
String bookname=request.getParameter("bookname");
String bookprice1=request.getParameter("price1");
String bookprice2=request.getParameter("price2");
if((sort==null||sort.length()==0)&&(bookname==null||bookname.length()==0)&&(bookprice1==null||bookprice1.length()==0))
try
{
//Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/U?serverTimezone=UTC","root","123456");
//Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery("select * from Books ");
while(rs.next())
{%>
<tr>
<td align="center"><%=rs.getString("Booknumber")%></td>
<td align="center"><%=rs.getString("Bookname")%></td>
<td align="center"><%=rs.getString("Bookprice")%></td>
<td align="center"><%=rs.getString("author")%></td>
<td align="center"><%=rs.getString("sort")%></td>
<td align="center"><a href="BuyServlet?id=<%=rs.getString("Booknumber") %>" >添加到购物车</a></td>
</tr>
<%
}
}
catch (Exception e)
{
out.println("get data error!<br>");
e.printStackTrace();
}
else if(sort!=null&&sort.length()>0)
{
sort=new String (sort.getBytes("iso-8859-1"),("utf-8"));
String sql= "select * from Books where sort='"+sort+"'";
try
{
ResultSet rs = stmt.executeQuery(sql);
while(rs.next())
{
%>
<tr>
<td><%=rs.getString("Booknumber")%></td>
<td><%=rs.getString("Bookname")%></td>
<td><%=rs.getString("Bookprice")%></td>
<td><%=rs.getString("author")%></td>
<td><%=rs.getString("sort")%></td>
<td><a href="BuyServlet?id=<%=rs.getString("Booknumber") %>" >添加到购物车</a></td>
</tr>
<%
}
}catch(Exception e)
{
e.printStackTrace();
}
}
else if(bookname!=null&&bookname.length()>0)
{
bookname=new String (bookname.getBytes("iso-8859-1"),("utf-8"));
String sql= "select * from Books where bookname='"+bookname+"'";
try
{
ResultSet rs = stmt.executeQuery(sql);
while(rs.next())
{
%>
<tr>
<td><%=rs.getString("Booknumber")%></td>
<td><%=rs.getString("Bookname")%></td>
<td><%=rs.getString("Bookprice")%></td>
<td><%=rs.getString("author")%></td>
<td><%=rs.getString("sort")%></td>
<td><a href="BuyServlet?id=<%=rs.getString("Booknumber") %>" >添加到购物车</a></td>
</tr>
<%
}
}catch(Exception e)
{
e.printStackTrace();
}
}
else
{
String sql= "select * from Books where bookprice>'"+bookprice1+"'"+"and bookprice<'"+bookprice2+"'";
try
{
ResultSet rs = stmt.executeQuery(sql);
while(rs.next())
{
%>
<tr>
<td><%=rs.getString("Booknumber")%></td>
<td><%=rs.getString("Bookname")%></td>
<td><%=rs.getString("Bookprice")%></td>
<td><%=rs.getString("author")%></td>
<td><%=rs.getString("sort")%></td>
<td><a href="BuyServlet?id=<%=rs.getString("Booknumber") %>" >添加到购物车</a></td>
</tr>
<%
}
}catch(Exception e)
{
e.printStackTrace();
}
}
%>
</table>
</body>
</html>
注册界面
<head>
<title>购书系统</title> <link type="text/css" rel="stylesheet" href="a.css">
</head>
<body>
<div class="content">
<h1>购书系统</h1>
<form action="RegServlet" method="post" onsubmit="return reg(this)";>
账 户:<input type="text" name="username" class="input-css"/><br/>
密 码:<input type="password" name="password" class="input-css"/><br/>
确认密码:<input type="password" name="repassword" class="input-css"/><br/>
<input type="submit" value="注册" class=btn>
<input type="reset" value="重置" class=btn>
</form>
</div>
</body>
package la;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
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 com.mysql.cj.xdevapi.Statement;
@WebServlet("/RegServlet")
public class RegServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private Connection conn;
public RegServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
public void init() throws ServletException{
super.init();
try{
Class.forName("com.mysql.cj.jdbc.Driver");
}catch (Exception e){
e.printStackTrace();
}
try{
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/U?serverTimezone=UTC","root","123456");
System.out.println("数据库连接成功");
}catch(Exception e){
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//doGet(request, response);
response.setContentType("text/html");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String username=request.getParameter("username");
String password=request.getParameter("password");
String password2=request.getParameter("repassword");
if(conn!=null)
{
int c=username.length();
int d=password.length();
if(c==0||d==0||username==null||password==null)
{
PrintWriter out=response.getWriter();
out.println("<script>");//输出script标签
out.println("alert('用户或密码不能为空,请重新输入!');");//js语句:输出alert语句
out.println("history.back();");//js语句:输出网页回退语句
//out.print("setTimeout('history.go(-1)', '1000')");
out.println("</script>");//输出script结尾标签
}
else
{
java.sql.Statement statement = null;
ResultSet rs = null;
try {
//2. 获取Statement
statement = conn.createStatement();
//3. 准备SQL
String sql = "SELECT username FROM user";
//4. 执行查询,得到ResultSet
rs = ((java.sql.Statement) statement).executeQuery(sql);
while(rs.next())
{
String a=rs.getString("username");
if(a.equals(username))
{
PrintWriter out=response.getWriter();
out.println("<script>");//输出script标签
out.println("alert('用户名已存在,请重新输入!');");//js语句:输出alert语句
out.println("history.back();");//js语句:输出网页回退语句
//out.print("setTimeout('history.go(-1)', '1000')");
out.println("</script>");//输出script结尾标签
}
}
} catch (SQLException e) {
e.printStackTrace();
}
if(password.equals(password2)==false)
{
PrintWriter out=response.getWriter();
out.println("<script>");//输出script标签
out.println("alert('两次输入的密码密码不一致,请重新输入!');");//js语句:输出alert语句
out.println("history.back();");//js语句:输出网页回退语句
//out.print("setTimeout('history.go(-1)', '1000')");
out.println("</script>");//输出script结尾标签
}
else
{
try{
String sql ="insert into user(username,password)" + "values(?,?)";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
ps.executeUpdate();
PrintWriter out=response.getWriter();
out.print("<h1 aling='center'>");
out.print(username+"注册成功!");
out.print("</h1>");
out.print("<br>");
out.print("<h2 aling='center'>");
out.print("<a href='login.jsp'>");
out.print("去登陆");
//out.print("</a>");
out.print("</h2>");
out.flush();
out.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
else
{
response.sendError(500,"数据库连接出错!");
}
}
}
修改密码界面
<body>
<head>
<link type="text/css" rel="stylesheet" href="a.css">
</head>
<div class="content">
<h1>购书系统</h1>
<form method="post" action="AltServlet">
账户: <input type="text" name="username" class="input-css"/><br/>
原 密码:<input type="password" name="oldpassword" class="input-css"/><br/>
新密码:<input type="password" name="newpassword" class="input-css"><br/>
确认密码:<input type="password" name="renewpassword" class="input-css"><br/>
<input type="submit" value="确定" class="btn">
</form>
</div>
</body>
提交到AlServlet
package la;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/AltServlet")
public class AltServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private Connection conn;
public AltServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
public void init() throws ServletException{
super.init();
try{
Class.forName("com.mysql.cj.jdbc.Driver");
}catch (Exception e){
e.printStackTrace();
}
try{
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/U?serverTimezone=UTC","root","123456");
System.out.println("数据库连接成功");
}catch(Exception e){
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//doGet(request, response);
response.setContentType("text/html");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String username=request.getParameter("username");
String password=request.getParameter("oldpassword");
String password2=request.getParameter("newpassword");
String password3=request.getParameter("renewpassword");
if(conn!=null)
{
int c=username.length();
int d=password.length();
if(c==0||d==0||username==null||password==null)
{
PrintWriter out=response.getWriter();
out.println("<script>");//输出script标签
out.println("alert('用户或密码不能为空,请重新输入!');");//js语句:输出alert语句
out.println("history.back();");//js语句:输出网页回退语句
//out.print("setTimeout('history.go(-1)', '1000')");
out.println("</script>");//输出script结尾标签
}
else
{
java.sql.Statement statement = null;
java.sql.Statement statement1=null;
java.sql.Statement statement2=null;
ResultSet rs = null;
try {
//2. 获取Statement
statement = conn.createStatement();
//3. 准备SQL
String sql = "SELECT username FROM user";
//4. 执行查询,得到ResultSet
rs = ((java.sql.Statement) statement).executeQuery(sql);
boolean flag=false;
while(rs.next())
{
String a=rs.getString("username");
if(a.equals(username))
flag=true;
}
if(flag==false)
{
PrintWriter out=response.getWriter();
out.println("<script>");//输出script标签
out.println("alert('用户名不存在,请重新输入!');");//js语句:输出alert语句
out.println("history.back();");//js语句:输出网页回退语句
//out.print("setTimeout('history.go(-1)', '1000')");
out.println("</script>");//输出script结尾标签
}
} catch (SQLException e) {
e.printStackTrace();
}
try
{
statement1=conn.createStatement();
String sql1="select password from user where username='"+username+"'";
rs = ((java.sql.Statement) statement1).executeQuery(sql1);
//System.out.println("0000000000000000");
while(rs.next())
{
String b=rs.getString(1);
System.out.println("b="+b);
if(b.equals(password)!=true)
{
PrintWriter out=response.getWriter();
out.println("<script>");//输出script标签
out.println("alert('密码不正确,请重新输入!');");//js语句:输出alert语句
out.println("history.back();");//js语句:输出网页回退语句
//out.print("setTimeout('history.go(-1)', '1000')");
out.println("</script>");//输出script结尾标签
}
}
}catch (SQLException e) {
e.printStackTrace();
}
if(password2.equals(password3)==false)
{
PrintWriter out=response.getWriter();
out.println("<script>");//输出script标签
out.println("alert('两次输入的密码密码不一致,请重新输入!');");//js语句:输出alert语句
out.println("history.back();");//js语句:输出网页回退语句
//out.print("setTimeout('history.go(-1)', '1000')");
out.println("</script>");//输出script结尾标签
}
else
{
try{
statement2 = conn.createStatement();
String sql2="update user set password='" + password2+"' where username='"+username+"'";
int i=statement2.executeUpdate(sql2);
System.out.println(i);
if(i==1){
PrintWriter out=response.getWriter();
out.print("<h1 aling='center'>");
out.print(username+"密码修改成功!");
out.print("</h1>");
out.print("<br>");
out.print("<h2 aling='center'>");
out.print("<a href='login.jsp'>");
out.print("去登陆");
//out.print("</a>");
out.print("</h2>");
}
else
{
PrintWriter out=response.getWriter();
out.println("<script>");//输出script标签
out.println("alert('密码修改失败');");//js语句:输出alert语句
out.println("history.back();");//js语句:输出网页回退语句
//out.print("setTimeout('history.go(-1)', '1000')");
out.println("</script>");//输出script结尾标签
}
PrintWriter out=response.getWriter();
out.flush();
out.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
else
{
response.sendError(500,"数据库连接出错!");
}
}
}
主界面通过a标签来与Buyservlet交互
package la;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.Map;
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 javax.servlet.http.HttpSession;
@WebServlet("/BuyServlet")
public class BuyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public BuyServlet() {
super();
}
public void init() throws ServletException{
super.init();
try{
Class.forName("com.mysql.cj.jdbc.Driver");
}catch (Exception e){
e.printStackTrace();
}
try{
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/U?serverTimezone=UTC","root","123456");
System.out.println("数据库连接成功");
}catch(Exception e){
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String id1 = request.getParameter("id");
int id = Integer.parseInt(id1);
String[] names = {"三国","西游记","红楼梦","数据结构","计算机组成原理","数据库","数理统计","高数","牛顿的书"};
String name = names[id-1];
//判断是否是第一次购物
Map<String,Integer> map = (Map<String,Integer>)request.getSession().getAttribute("cart");
if(map==null)
{
map = new HashMap<String, Integer>();
map.put(name, 1);
}
else
{
//不是第一次,判断购物车是否有相同名称的商品
if(map.containsKey(name))
{
int num = map.get(name);
map.put(name, num+1);
}else
{
//直接放名称和数量
map.put(name, 1);
}
}
//把购物车放到session里面
request.getSession().setAttribute("cart", map);
//输出两个超链接,继续购物和去结算
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.println("<script>");//输出script标签
out.println("alert('添加成功!');");//js语句:输出alert语句
out.println("history.back();");//js语句:输出网页回退语句
//out.print("setTimeout('history.go(-1)', '1000')");
out.println("</script>");//输出script结尾标签
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
showCar
<head>
<link type="text/css" rel="stylesheet" href="a.css">
<title>购书系统</title>
<body>
<div class="content">
<h1>购物系统</h1>
</div>
<div class="ys1">
<a href="clear">清空购物车</a>
<a href="bookstore.jsp">继续购物</a>
</div>
<div class="ys1">
<%
Map<String,Integer> map =( Map<String,Integer>) request.getSession().getAttribute("cart");
if(map==null)
{
%>
<h2>没有任何购物信息</h2>
<%
}else
{
//有购物信息,显示名称和数量
Set<String> keys = map.keySet();
String id=request.getParameter("id");
if(id==null);
else
System.out.print(id);
for(String key : keys)
{
if(key.equals(id))
{
keys.remove(id);
}
else
{
int num = map.get(key);
%>
<h3>
名称:<%=key%>
数量:<%=num %>
<a href="showCar.jsp?id=<%=key%>">删除</a>
</h3>
<%}%>
<%
}
}
%>
</div>
</body>
注销
<body>
<head>
<link type="text/css" rel="stylesheet" href="a.css">
<title>购书系统</title>
</head>
<body>
<div class="content">
<h1>购书系统</h1>
<form method="post" action="CheckupServlet">
账户:<input type="text" name="username" class="input-css"/><br/>
密码:<input type="password" name="password" class="input-css"/><br/>
<input type="submit" value="登录" class="btn">
<a href="Register.jsp" >注册</a>
<a href="bookstore.jsp">以游客身份访问</a>
</form>
</div>
</body>
</html>
package la;
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;
import javax.servlet.http.HttpSession;
@WebServlet("/clear")
public class clear extends HttpServlet {
private static final long serialVersionUID = 1L;
public clear() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
HttpSession session = request.getSession();
//销毁session
session.invalidate();
response.sendRedirect("showCar.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
下一篇: java md5及3des加密实现