概述
建立数据库表:
- 用户表:
CREATE TABLE `usertable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`uname` varchar(20) NOT NULL,
`password` varchar(15) NOT NULL,
`phone` varchar(20) DEFAULT NULL,
`birthday` date DEFAULT NULL,
`address` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
- 商品表:
CREATE TABLE `items` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(50) default NULL,
`city` varchar(50) default NULL,
`price` int(11) default NULL,
`number` int(11) default NULL,
`picture` varchar(500) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
jsp页面主要代码:
注册页面:
<form action="Doregister" method="post">
<h1 align="center" style="color: pink">欢迎注册!</h1>
<hr color="#F4F4F4"/>
<div class="down">
<div class="uname">   请输入用户名 </div>
<input type="text" id="txt1" name="username" size="35" placeholder="     您的账户名" class="username"/><span id='sp1'></span>
<div class="pwd">    设 置 密 码</div>
<input type="text" id="txt2" name="password" size="35" placeholder="     建议使用两种或两种以上的字符组合" class="password"/><span id='sp2'></span>
<div class="bir">      生日</div>
<input type="text" id="txt3" name="birth" size="35" placeholder="     输入生日XXXX-YY-ZZ" class="birth"/><span id='sp3'></span>
<div class="ph">      手机号码</div>
<input type="text" id="txt4" name="phone" size="35" placeholder="     输入手机号+86" class="phone"/><span id='sp4'></span>
<div class="add">     地址</div>
<input type="text" name="address" size="35" placeholder="     输入住址" class="address"/>
<input type="submit" value="注 册" class="ZC"/>
</div>
</form>
<script type="text/javascript">
var rg1=/^1[345789]d{9}$/;//^匹配字符串开头,$结尾;[]字符类,匹配所包含的任意一个字符
var txt3=document.querySelector('#txt4');
var sp3=document.querySelector('#sp4');
//注册事件 失去焦点
txt3.onblur=function(){
//获得用户输入
var str=txt3.value;
//匹配
if(rg1.test(str)){
sp3.innerHTML="手机号输入正确";
sp3.className='success';
}else{
sp3.innerHTML="手机号格式错误,请重新输入";
sp3.className='error';
}
}
var txt1=document.getElementById('txt1');
var sp1=document.getElementById('sp1');
//用户名正则
var username=/^[a-zA-Z0-9_]{6,15}$/;
//失去焦点 onblur
txt1.onblur=function(){
var str=txt1.value;
//test方法验证
if(username.test(str)){
sp1.innerHTML='用户名输入正确';
sp1.className='success'
}else{
sp1.innerHTML='用户名输入错误,请重新输入';
sp1.className='error';
}
}
var txt2=document.getElementById('txt2');
var sp2=document.getElementById('sp2');
//正则
var password=/^[a-zA-Z0-9_]{6,15}$/;
//失去焦点 onblur
txt2.onblur=function(){
var str=txt2.value;
//test方法验证
if(password.test(str)){
sp2.innerHTML='密码输入正确';
sp2.className='success'
}else{
sp2.innerHTML='密码输入错误,请重新输入';
sp2.className='error';
}
}
var....rg4=/^(?:19d{2}|20(?:[0-1]d|2[0]))-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]d|3[01])$/;//^匹配字符串开头,$结尾;[]字符类,匹配所包含的任意一个字符
var txt4=document.querySelector('#txt3');
var sp4=document.querySelector('#sp3');
//注册事件 失去焦点
txt4.onblur=function(){
//获得输入
var str=txt4.value;
//匹配
if(rg4.test(str)){
sp4.innerHTML="生日输入正确";
sp4.className='success';
}else{
sp4.innerHTML="生日格式错误,请重新输入";
sp4.className='error';
}
}
</script>
</div>
登录界面:
<form action="Dologin" method="post">
<h1 align="center" style="color: pink">欢迎登录购物系统!</h1>
<hr color="#F4F4F4"/>
<div class="down">
<div class="uname">    用  户  名</div>
<input type="text" name="username" size="35" placeholder="     您的账户名和登录名" class="username"/>
<div class="pwd">    设 置 密 码</div>
<input type="text" name="password" size="35" placeholder="     建议使用两种或两种以上的字符组合" class="password"/> <div class="ma">      验证码</div>
<input type="text" name="ma1" size="35" placeholder="     输入验证码" class="ma1"/>
<img src="CheckServ" class="pic"/>
<input type="submit" value="登 录" class="ZC"/>
</div></form>
商品展示页:
<!-- 商品循环开始 -->
<%
GoodDao goodDao=new GoodDao();
List<Goods> list=goodDao.getGoodList();
if(list!=null&&list.size()>0){
for(int i=0;i<list.size();i++){
Goods goods=list.get(i);
%> <div>
<dl>
<dt>
<a href="details.jsp?id=<%=goods.getId() %>"><img src="images/<%=goods.getPicture() %>" width="120" height="90" border="1"/></a>
</dt>
<dd class="dd_name"><%=goods.getName() %></dd>
<dd class="dd_city">产地:<%=goods.getCity() %> 价格:¥<%=goods.getPrice() %></dd>
</dl>
</div>
<!-- 商品循环结束 -->
<% } } %>
商品详情页面:
<script type="text/javascript" src="js/lhgcore.js"></script>
<script type="text/javascript" src="js/lhgdialog.js"></script>
<script language="javascript" type="text/javascript">
function selflog_show(id)
{
var num = document.getElementById("number").value;
J.dialog.get({id: 'haoyue_creat',title: '购物成功',width: 600,height:400, link: '<%=path%>/CartServlet?id='+id+'&num='+num+'&action=add', cover:true});
}
function add()//增加数量+
{
var num = parseInt(document.getElementById("number").value);
if(num<100)
{
document.getElementById("number").value = ++num;
}
}
function sub()//减少数量图标-
{
var num = parseInt(document.getElementById("number").value);
if(num>1)
{
document.getElementById("number").value = --num;
}
}
</script>
<!-- 商品详情 -->
<%
GoodDao goodDao=new GoodDao();
Goods....goods=goodDao.findById(Integer.parseInt(request.getParameter("id")));
if(goods!=null){
%>
<td width="70%" valign="top">
<table>
<tr>
<td rowspan="4"><img src="images/<%=goods.getPicture() %>"width="200" height="160"/></td>
</tr>
<tr>
<td><B><%=goods.getName() %></B></td>
</tr>
<tr>
<td>产地:<%=goods.getCity() %></td>
</tr>
<tr>
<td>价格:<%=goods.getPrice() %></td>
</tr>
<tr>
<td>购买数量:<span id="sub" onclick="sub();">-</span><input type="text" id="number" name="number" value="1" size="2"/><span id="add" onclick="add();">+</span></td>
</tr>
</table>
<div id="cart">
<img src="images/buy_now.png">
<a href="javascript:selflog_show(<%=goods.getId()%>)"><img src="images/in_cart.png"></a>
<a href="CartServlet?action=show"><img src="images/view_cart.jpg"/></a>
</div>
<% } %>
<%
String list ="";
//从客户端获得Cookies集合
Cookie[] cookies = request.getCookies();
//遍历这个Cookies集合
if(cookies!=null&&cookies.length>0)
{
for(Cookie c:cookies)
{
if(c.getName().equals("ListViewCookie"))
{
list = c.getValue();
} }
}
list+=request.getParameter("id")+"-";
//如果浏览记录超过1000条,清零.
String[] arr = list.split("-");
if(arr!=null&&arr.length>0)
{
if(arr.length>=1000)
{
list="";
} }
Cookie cookie = new Cookie("ListViewCookie",list);
response.addCookie(cookie);
%>
<!-- 浏览过的商品 -->
<td width="30%" bgcolor="#EEE" align="center">
<br>
<b><font color="#FF7F00">您浏览过的商品</font></b><br>
<!-- 循环开始 -->
<%
ArrayList<Goods> itemsList =goodDao.getViewList(list);
if(itemsList != null && itemsList.size() > 0) {
for(Goods i : itemsList) {
%>
<div>
<dl>
<dt>
<a href="details.jsp?id=<%=i.getId()%>"><img src="images/<%=i.getPicture() %>" width="120" height="90" border="1"/></a>
</dt>
<dd class="dd_name"><%=i.getName() %></dd>
<dd class="dd_city">产地:<%=i.getCity() %> 价格:¥<%=i.getPrice() %> </dd>
</dl>
</div>
<%
}
}
%>
<!-- 循环结束 -->
购物车页面:
<script language="javascript">
function delcfm() {
if (!confirm("确认要删除?")) {
window.event.returnValue = false;
}
}
</script>
<%
//判断session中是否有购物车对象
if(request.getSession().getAttribute("cart")!=null){ %>
<!-- 循环的开始 -->
<%
Cart cart=(Cart)request.getSession().getAttribute("cart");
HashMap<Goods,Integer> good=cart.getGoods();
Set<Goods> goods=good.keySet();
Iterator<Goods> it=goods.iterator();
while(it.hasNext()){
Goods i=it.next();
%>
<tr name="products" id="product_id_1">
<td class="thumb"><img src="images/<%=i.getPicture() %>"width="150" height="120"/><a href="details.jsp?id=<%=i.getId()%>">
<%=i.getName()%></a></td>
<td class="number"><%=i.getPrice() %></td>
<td class="price" id="price_id_1">
<span><%=i.getPrice()*good.get(i) %></span>
<input type="hidden" value="" />
</td>
<td class="number">
<%=good.get(i) %>
</td>
<td class="delete">
<a..href="CartServlet?action=delete&id=<%=i.getId() %>"οnclick="delcfm();">删除</a>
</td></tr>
<%
}
%>
<!-- 循环的结束 -->
Dao层及Servlet层设计
Gooddao:
Connection conn;
PreparedStatement pst;
ResultSet rs;
public List<Goods> find(Integer id,String name,String city){
conn=DButil.getConn();
List<Goods> goods=new ArrayList<Goods>();
String sql="select * from items where 1=1";
if(id!=null)
{
sql=sql+" and id='"+id+"'";
}
if(name!=null){
sql=sql+" and name='"+name+"'";
}
if(city!=null){
sql=sql+" and city='"+city+"'";
}
System.out.println(sql);
try {
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
//处理结果集
while(rs.next()){
Goods good=new Goods(rs.getInt("id"),
rs.getString("name"),
rs.getString("city"),
rs.getInt("price"),
rs.getInt("number"), rs.getString("picture")
goods.add(good);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DButil.closeAll(conn, pst, rs);
}
return goods;
}
/**
* 根据id查询商品
* @param id
* @return
*/
public Goods findById(Integer id){
Goods goods=null;//创建用户对象
String sql="select * from items where id='"+id+"' ";
System.out.println(sql);
try {
conn=DButil.getConn();
//执行sql语句
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
if(rs.next()) {
goods=new Goods();
goods.setId(rs.getInt("id"));
goods.setName(rs.getString("name"));
goods.setCity(rs.getString("city"));
goods.setNumber(rs.getInt("number"));
goods.setPrice(rs.getInt("price"));
goods.setPicture(rs.getString("picture"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DButil.closeAll(conn, pst, rs);
}
return goods;
}
//获取所有商品
public List<Goods> getGoodList( )
{
String sql="select * from items";
List<Goods> List = new ArrayList<>();
Goods goods = null ;
try
{
conn=DButil.getConn();
//执行sql语句
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
while(rs.next()) {
goods=new Goods();
goods.setId(rs.getInt("id"));
goods.setName(rs.getString("name"));
goods.setCity(rs.getString("city"));
goods.setNumber(rs.getInt("number"));
goods.setPrice(rs.getInt("price"));
goods.setPicture(rs.getString("picture"));
List.add(goods);
}
for(int i=0;i<List.size();i++) {
System.out.println(List.get(i));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DButil.closeAll(conn, pst, rs);
}
return List ;
}
//获取最近浏览的前五条商品信息
public ArrayList<Goods> getViewList(String list)
{
System.out.println("list:"+list);
ArrayList<Goods> itemlist = new ArrayList<Goods>();
int iCount=5; //每次返回前五条记录
if(list!=null&&list.length()>0)
{
String[] arr = list.split("-");
System.out.println("arr.length="+arr.length);
//如果商品记录大于等于5条
if(arr.length>=5)
{
for(int i=arr.length-1;i>=arr.length-iCount;i--)
{
itemlist.add(findById(Integer.parseInt(arr[i])));
}
}
else
{
for(int i=arr.length-1;i>=0;i--)
{
itemlist.add(findById(Integer.parseInt(arr[i])));
}
}
return itemlist;
}else
{
return null;
}
}
po层:
Goods:
private String name; // 商品名称
private String city; // 产地
private int price; // 价格
private int number; // 库存
private String picture; // 商品图片
购物车cart:
//购物车集合
private HashMap<Goods, Integer> good;
//购物车金额
private double totalPrice;
public Cart() {
// TODO Auto-generated constructor stub
good=new HashMap<Goods,Integer>();
totalPrice=0.0;
}
public HashMap<Goods, Integer> getGoods() {
return good;
}
public void setGoods(HashMap<Goods, Integer> goods) {
this.good = goods;
}
public double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(double totalPrice) {
this.totalPrice = totalPrice;
}
//添加商品到购物车
public boolean addGoodCart(Goods goods,int number) {
if(good.containsKey(goods)) {
good.put(goods, good.get(goods)+number);
}else {
good.put(goods, number);
}
TotalCartPrice();//重新计算购物车总金额
return true;
}
//删除商品
public boolean removeGoodCart(Goods goods) {
good.remove(goods);
TotalCartPrice();//重新计算购物车总金额
return true;
}
//统计购物车总金额
public double TotalCartPrice() {
double sum=0.0;
Set<Goods> keys=good.keySet();//获得键的集合
Iterator<Goods> it=keys.iterator();//获得迭代器对象
while (it.hasNext()) {
Goods i=it.next();
sum+=i.getPrice()*good.get(i);
}
this.setTotalPrice(sum);//设置购物车的总金额
return this.getTotalPrice();
}
Servlet层:
CartServlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//doGet(request, response);
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
if(request.getParameter("action")!=null) {
this.action=request.getParameter("action");
if(action.equals("add")) {//添加商品进购物车
try {
if(addToCart(request,response)) {
request.getRequestDispatcher("/success.jsp").forward(request, response);
}else {
request.getRequestDispatcher("/false.jsp").forward(request, response);
}
}catch (Exception e) {
e.printStackTrace();
}
}
if("show".equals(action)) {//显示购物车
try {
request.getRequestDispatcher("/cart.jsp").forward(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if("delete".equals(action)) {//删除购物车商品
if(deleteFromCart(request,response)){
request.getRequestDispatcher("/cart.jsp").forward(request, response);
}
}
if("clear".equals(action)) {//清空购物车商品
HttpSession session = request.getSession();
//清除session域中的cart对象
session.removeAttribute("cart");
request.getRequestDispatcher("/cart.jsp").forward(request, response);
}
}
//添加商品进购物车
private boolean addToCart(HttpServletRequest request, HttpServletResponse response) {
String id=request.getParameter("id");
String number=request.getParameter("num");
Goods goods=goodDao.findById(Integer.parseInt(id));
//是否是第一次给购物车添加商品
if(request.getSession().getAttribute("cart")==null) {
Cart cart=new Cart();
request.getSession().setAttribute("cart", cart);
}
Cart cart=(Cart)request.getSession().getAttribute("cart");
if(cart.addGoodCart(goods, Integer.parseInt(number))) {
return true;
}else {
return false;
}
}
//删除购物车中商品
private boolean deleteFromCart(HttpServletRequest request, HttpServletResponse response) {
String id=request.getParameter("id");
Cart cart=(Cart)request.getSession().getAttribute("cart");
Goods goods=goodDao.findById(Integer.parseInt(id));
if(cart.removeGoodCart(goods)) {
return true;
}else {
return false;
}
}
}
Doregister:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
PrintWriter pw=response.getWriter();
//获得用户请求参数
String uname=request.getParameter("username");
String pwd1=request.getParameter("password1");
String pwd2=request.getParameter("password2");
String birth=request.getParameter("birth");
String phone=request.getParameter("phone");
String address=request.getParameter("address");
//如果用户名或密码为空 返回登录界面
if(uname==null||pwd1==null||pwd2==null||birth==null||phone==null||address==null||!pwd1.equals(pwd2)) {
pw.write("<script language='javascript'>alert('注册信息不能为空!')</script>");
response.sendRedirect("register.jsp");
return;
}
Userbean userbean=new Userbean();
userbean.setUname(uname);
userbean.setPassword(pwd1);
SimpleDateFormat sFormat=new SimpleDateFormat("yyyy-MM-dd");
Date bir=null;
try {
bir = sFormat.parse(birth);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
userbean.setBirthday(bir);
userbean.setPhone(phone);
userbean.setAddress(address);
UserDao userDao=new UserDao();
int result=userDao.addUser(userbean);
//判断
if(result!=0) {
//登录成功
response.sendRedirect("login.jsp");
}else {
//登录失败
response.sendRedirect("register.jsp");
}
}
}
Dologin:
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");
PrintWriter out=response.getWriter();
PrintWriter pw=response.getWriter();
request.setCharacterEncoding("utf-8");
//获得参数
String uname=request.getParameter("username");
String pwd=request.getParameter("password");
String ccode=request.getParameter("ma1");
//取session中的验证码
HttpSession session=request.getSession();
String scode=(String)session.getAttribute("checkcode");
if(ccode.equals(scode)) {
UserDao userDao=new UserDao();
Userbean userbean=userDao.selecetBysome(uname, pwd);
if(uname==null || pwd==null) {
pw.write("<script language='javascript'>alert('用户名或密码为空!')</script>");
request.getRequestDispatcher("login.jsp").include(request, response);
}else {
//判断
if(userbean!=null) {
//登录成功
session.setAttribute("username", userbean.getUname());
request.getRequestDispatcher("index.jsp").include(request, response);
}else {
//登录失败
pw.write("<script language='javascript'>alert('用户名或密码错误!')</script>");
request.getRequestDispatcher("login.jsp").include(request, response);
}
}
}else {
//验证码不正确
pw.write("<script language='javascript'>alert('验证码错误!')</script>");
//response.sendRedirect("login.jsp");
request.getRequestDispatcher("login.jsp").include(request, response);
}
}
Util连接类:
public static Connection getConn(){
java.sql.Connection conn=null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/test";
String username="root";
String password="root";
// conn=DriverManager.getConnection(url,username,password);
conn=DriverManager.getConnection(url,username,password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
运行效果图
总结
在编写details.jsp时,先是因为对J.dialog.get方法的不熟悉没有导入相应的js文件而导致添加商品成功窗口无法弹出,然后在设置显示最近浏览的五件商品中一开始设置list以”,”分割,但是cookie规范中将“,”识别为非法字符串,后将list以“-”分割,成功实现显示最近浏览的五件商品。实验整体实现比较简单,都是最基本的知识。
完整代码获取:https://download.csdn.net/download/qq_45664450/19688571?spm=1001.2014.3001.5501
最后
以上就是秀丽大雁为你收集整理的Jsp+Servlet+Mysql实现简易购物车系统的全部内容,希望文章能够帮你解决Jsp+Servlet+Mysql实现简易购物车系统所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复