今天练习了一个登陆,然后能查看商品,查看购物车并且进行相关简单操作的小程序。
登陆的用户名为admin,密码为123
大致程序清单:
数据库为MySQL:
建一个名为goods的表
MySQL语句:
create database shopcar;
----------
use shopcar;
----------
create table goods(
id int not null auto_increment primary key,
gname varchar(25),
price dec(10,2),
total int,
pic varchar(56)
);
----------
insert into goods(gname,price,total,pic) values('蓝色拖鞋',22.5,100,'ups/pic01.jpg');
insert into goods(gname,price,total,pic) values('黑色男士衬衫',85,500,'ups/pic02.jpg');
insert into goods(gname,price,total,pic) values('浴帽',18,65,'ups/pic03.jpg');
insert into goods(gname,price,total,pic) values('蓝牙耳机',200,90,'ups/pic04.jpg');
insert into goods(gname,price,total,pic) values('男童T-shit',40,1000,'ups/pic05.jpg');
----------
写登陆页面:
login.html
<!DOCTYPE html>
<!--登录页面 主页 -->
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<center>
<form action="checkLogin" method="post">
用户名:<input type="text" name="uname" required="required" pattern="\w{3,12}"/><br/><!-- required的意思是此空为必填项,pattern后面的是正则表达式 -->
密码:<input type="password" name="upwd" required/><br/>
<button type="submit">登录</button>
</form>
</center>
</body>
</html>
C3p0配置:
C3p0.properities
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.user=root
c3p0.password=mysql
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/shopcar
c3p0.initialPoolSize=3
c3p0.maxPoolSize=10
c3p0.minPoolSize=2
Java程序:
先创立一个Goods类:
在com.shop.pojo下创立Goods.java
package com.shop.pojo;
//商品类,包括商品的所有信息,设置get和set方法
import java.io.Serializable;
import java.math.BigDecimal;
public class Goods implements Serializable
{
private int id;
private String gname;
private BigDecimal price;
private int total;
private String pic;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGname() {
return gname;
}
public void setGname(String gname) {
this.gname = gname;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
}
然后是Goods类的接口:
在com.shop.dao下建立GoodsDao.java
package com.shop.dao;
//商品方法的接口,有得到所有商品、根据id获得商品对象的抽象方法。
import java.util.List;
import com.shop.pojo.Goods;
public interface GoodsDao {
public List<Goods> getAll();
public Goods getById(int id);
}
Goods类的接口的实现类:
在com.shop.dao下建立GoodsDaoImp.java
package com.shop.dao;
//商品方法的实现类,有得到所有商品、根据id获得商品对象的方法。
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.shop.pojo.Goods;
public class GoodsDaoImp implements GoodsDao
{
private static ComboPooledDataSource ds=new ComboPooledDataSource();
private QueryRunner run=new QueryRunner(ds);
@Override
public List<Goods> getAll()
{
String sql="select * from goods";
List<Goods> list=null;
try {
list=run.query(sql, new BeanListHandler<Goods>(Goods.class));//new了一个BeanListHandler对象。可以将查询到的Goods的信息存到list中
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
@Override
public Goods getById(int id)
{
String sql="select * from goods where id=?";
Goods list=null;
try {
list=run.query(sql, new BeanHandler<Goods>(Goods.class),id);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
}
检查是否登录成功的Servlet:
在com.shop.servlet下建立CheckLoginServlet.java
package com.shop.servlet;
//检查登录是否成功的Servlet,登录成功后跳转到ShowGoodsServlet,失败则跳转到login.html
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.shop.dao.GoodsDaoImp;
import com.shop.pojo.Goods;
@WebServlet("/checkLogin")
public class CheckLoginServlet extends HttpServlet
{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
HttpSession session=req.getSession();
String uname=null!=req.getParameter("uname")?req.getParameter("uname"):"";
String upwd=null!=req.getParameter("upwd")?req.getParameter("upwd"):"";
if("admin".equals(uname)&&"123".equals(upwd))
{
session.setAttribute("loged", uname);//设置一个session
Cookie cookie=new Cookie("uname",uname);//新建一个cookie对象
cookie.setMaxAge(60*60*60*60);//cookie的生命周期
resp.addCookie(cookie);//向resp中加入一个cookie
req.getRequestDispatcher("showgoods").forward(req, resp);//向showgoods页面forward req 和 resp。
}else
{
resp.sendRedirect("login.html");//返回登录页面
}
}
}
商品显示页面:
在com.shop.servlet下建立ShowGoodsServlet.java
package com.shop.servlet;
//输出商品页面的Servlet,显示商品信息
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
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;
import com.shop.dao.GoodsDao;
import com.shop.dao.GoodsDaoImp;
import com.shop.pojo.Goods;
@WebServlet("/showgoods")
public class ShowGoodsServlet extends HttpServlet {
private GoodsDao gd=new GoodsDaoImp();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");//箱客户端返回数据是text/html类型,编码是utf-8。
req.setCharacterEncoding("utf-8");//读取req的时候用utf-8,避免乱码
PrintWriter out=resp.getWriter();//输出流,文字输出流
HttpSession session=req.getSession();//得到checkloginservlet传过来的session
String uname=(String)session.getAttribute("loged");//将session中的loged写入到uname字符串中,如果没有通过登录页面输入用户名的话,loged中将不会有信息,uname也为空
if(null==uname)//判断uname是否为空
{
//说明你没有通过验证
resp.sendRedirect("login.html");
}else
{//通过验证
List<Goods> list=gd.getAll();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println(" <meta charset='UTF-8'>");
out.println(" <title>商品列表</title>");
out.println(" <style type='text/css'>");
out.println(" *{ padding: 0;margin: 0;}");
out.println(" #container{width: 800px; height: 600px; border: 1px #ccc solid; margin: 0 auto;}");
out.println(" #container header{ height: 80px; border-bottom: 2px #ccc solid;}");
out.println(" #container header h1{ width: 600px; float: left; font-family: '微软雅黑'; line-height: 50px;}");
out.println(" #container header p{ width: 200px; float: right; line-height: 50px;}");
out.println(" #container article{ clear: both; padding: 10px;}");
out.println(" #container article section{ display: inline-block; margin-bottom: 10px; margin-right: 10px;}");
out.println(" #container article section label{ width: 130px; display: block;}");
out.println("</style>");
out.println("</head>");
out.println("<body>");
out.println(" <div id='container'>");
out.println(" <header>");
out.println(" <h1>商品列表</h1>");
out.println(" <p>");
out.println(" <a href='shopcar'>查看购物车</a> ");
out.println(" <a href='logout'>退出</a>");
out.println(" </p>");
out.println(" </header>");
out.println(" <article>");
if(null!=list)
{
for(Goods goods:list)//迭代list中的每一个goods对象
{
out.println(" <section>");
out.println(" <img src='"+goods.getPic()+"' width='150' height='150' />");//商品图片
out.println(" <form action='addCar' method='post'>");
out.println("<input type='hidden' name='gid' value='"+goods.getId()+"'/>");//商品id
out.println(" <label>"+goods.getGname()+"</label>");//商品名
out.println(" "+goods.getPrice()+" <select name='total'>");//商品价格,数量
for(int i=1;i<10;i++)//
out.println(" <option value='"+i+"'>"+i+"</option>");
out.println(" </select>");
out.println(" <button type='submit'>购买</button>");
out.println(" </form>");
out.println(" ");
out.println(" </section>");
}
}
out.println(" ");
out.println(" </article>");
out.println(" </div>");
out.println("</body>");
out.println("</html>");
}
out.close();
}
}
加入购物车Servlet:
在com.shop.servlet下建立AddCarsServlet.java
package com.shop.servlet;
//加入购物车这个行为的Servlet,成功的时候有提示
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
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;
import com.shop.dao.GoodsDao;
import com.shop.dao.GoodsDaoImp;
import com.shop.pojo.Goods;
@WebServlet("/addCar")
public class AddCarServlet extends HttpServlet {
private GoodsDao gd=new GoodsDaoImp();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
PrintWriter out=resp.getWriter();
String gid=null!=req.getParameter("gid")?req.getParameter("gid"):"";//得到商品id
HttpSession session=req.getSession();
if(gid.matches("\\d+"))
{
int id=Integer.parseInt(gid);
Goods goods=gd.getById(id);
goods.setTotal(Integer.parseInt(req.getParameter("total")));
List<Goods> shopcar=(List<Goods>)session.getAttribute("shopcar");
if(null==shopcar)shopcar=new ArrayList<Goods>();
shopcar.add(goods);
session.setAttribute("shopcar", shopcar);
out.println("<script>alert(\"加入成功!\");window.location='showgoods'</script>");//提示加入成功后跳转到ShowGoodsServlet
}else
{
out.println("<script>window.location='showgoods'</script>");//失败则没有提示
}
//resp.sendRedirect("showgoods");
out.close();
}
}
购物车清单:
在com.shop.servlet下建立CarListServlet.java
package com.shop.servlet;
//购物车显示页面
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.List;
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;
import com.shop.pojo.Goods;
@WebServlet("/shopcar")
public class CarListServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
PrintWriter out=resp.getWriter();
out.println("<h1>购物车,您选择的商品如下:</h1>");
HttpSession session=req.getSession();
List<Goods> list=(List<Goods>)session.getAttribute("shopcar");
if(null!=list)
{
int index=1;
for(int i=0;i<list.size();i++)
{
Goods goods=list.get(i);
out.println("<ul>");
out.println("<li>"+(index++)//商品列表的数字(购物车中的第几个商品)
+ "<img src='"+goods.getPic()+"' width='150' height='150' />");
out.println("<label>"+goods.getGname()+"</label>");
out.println(goods.getPrice()+" "+goods.getTotal()+"个"+(goods.getPrice().multiply(new BigDecimal(String.valueOf(goods.getTotal())))));
//得到商品的单价,数量,总价
out.println(" <a href='deleteCar?index="+i+"'>删除</a> </li> ");
out.println("</ul>");
out.println("<center><a href='showgoods'>返回</a></center>");
}
}else{
out.println("您的购物车为空");
}
out.close();
}
}
从购物车删除的Servlet:
在com.shop.servlet下建立DeleteCarServlet.java
package com.shop.servlet;
//删除购物车中的物品(行为)
import java.io.IOException;
import java.util.List;
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;
import com.shop.pojo.Goods;
@WebServlet("/deleteCar")
public class DeleteCarServlet extends HttpServlet
{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session=req.getSession();
List<Goods> list=(List<Goods>)session.getAttribute("shopcar");
if(null!=list)
{
list.remove(Integer.parseInt(req.getParameter("index")));//得到index对应的商品
}
resp.sendRedirect("shopcar");
}
}
登出Servlet:
在com.shop.servlet下建立LogoutServlet.java
package com.shop.servlet;
//登出行为
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;
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet
{
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
arg0.getSession().invalidate();//删除会话
arg1.sendRedirect("showgoods");
}
}
配置xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>servlet01</display-name>
<welcome-file-list>
<welcome-file>showgoods</welcome-file>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
程序运行截图:
初学者,如果发现有错误,请多指正~
如果有想联系我交流技术的,可以加我QQ:773669388。欢迎大家多多指点。