Javaweb如何使用struts2实现购物车功能?

导读:本篇文章讲解 Javaweb如何使用struts2实现购物车功能?,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

这里仅给出将商品放在session中的代码,如果你看过我前面用servlet放在数据库中的代码,这里想实现放在数据库中其实也很简单!!下面给出代码:
1.首先,我们要新建一个web工程如图(注意包名一定要符合命名规范):
在这里插入图片描述
Product中的代码:

public class Product {
	private Integer pid;
	private String pname;
	private int num;
	private float price;
	private float count;
	public Product() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Product(Integer pid, String pname, int num, float price, float count) {
		super();
		this.pid = pid;
		this.pname = pname;
		this.num = num;
		this.price = price;
		this.count = count;
	}
	public Integer getPid() {
		return pid;
	}
	public void setPid(Integer pid) {
		this.pid = pid;
	}
	public String getPname() {
		return pname;
	}
	public void setPname(String pname) {
		this.pname = pname;
	}
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}
	public float getPrice() {
		return price;
	}
	public void setPrice(float price) {
		this.price = price;
	}
	public float getCount() {
		this.count = this.price * this.num;
		return count;
	}
	public void setCount(float count) {
		this.count = count;
	}
}

ProductAction中的代码:

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.jboss.weld.servlet.ServletApiAbstraction;
import com.bean.Product;

public class ProductAction {
	private Product pd;
	private int index;
	private String path;
	public Product getPd() {
		return pd;
	}
	public void setPd(Product pd) {
		this.pd = pd;
	}
	public int getIndex() {
		return index;
	}
	public void setIndex(int index) {
		this.index = index;
	}
	public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}
	
	@Action(value="add_Product",results={
			@Result(name="ok",location="${path}",type="redirect"),
			@Result(name="fail",location="${path}",type="redirect")
	})
	public String add(){
		HttpSession session = ServletActionContext.getRequest().getSession();
		List<Product> list = (List<Product>) session.getAttribute("list");
		if (list == null) {
			list = new ArrayList<Product>();
		}
		if (list.add(pd)) {
			session.setAttribute("list", list);
			path = "findAll_Product";
			return "ok";
		}
		path = "fail.jsp";
		return "fail";
	}
	@Action(value="update_Product",results={
			@Result(name="ok",location="${path}",type="redirect"),
			@Result(name="fail",location="${path}",type="redirect")
	})
	public String update(){
		HttpSession session = ServletActionContext.getRequest().getSession();
		List<Product> list = (List<Product>) session.getAttribute("list");
		if (list != null) {
			list.set(pd.getPid(), pd);
			session.setAttribute("list", list);
			path = "findAll_Product";
			return "ok";
		}
		path = "fail.jsp";
		return "fail";
	}
	@Action(value="delByIndex_Product",results={
			@Result(name="ok",location="${path}",type="redirect"),
			@Result(name="fail",location="${path}",type="redirect")
	})
	public String delByIndex(){
		HttpSession session = ServletActionContext.getRequest().getSession();
		List<Product> list = (List<Product>) session.getAttribute("list");
		if (list != null) {
			list.remove(index);
			session.setAttribute("list", list);
			path = "findAll_Product";
			return "ok";
		}
		path = "fail.jsp";
		return "fail";
	}
	@Action(value="findByIndex_Product",results={
			@Result(name="ok",location="${path}",type="redirect"),
			@Result(name="fail",location="${path}",type="redirect")
	})
	public String findByIndex(){
		HttpSession session = ServletActionContext.getRequest().getSession();
		List<Product> list = (List<Product>) session.getAttribute("list");
		if (list != null) {
			Product oldPd = list.get(index);
			oldPd.setPid(index);
			session.setAttribute("oldPd", oldPd);
			path = "update.jsp";
			return "ok";
		}
		path = "fail.jsp";
		return "fail";
	}
	@Action(value="findAll_Product",results={
		@Result(name="ok",location="${path}",type="redirect"),
		@Result(name="fail",location="${path}",type="redirect"),
	})
	public String findAll(){
		float sum = 0f;
		HttpSession session = ServletActionContext.getRequest().getSession();
		List<Product> list = (List<Product>) session.getAttribute("list");
		if (list != null) {
			for (Product pd : list) {
				sum+=pd.getCount();
			}
			session.setAttribute("sum", sum);
			path = "list.jsp";
			return "ok";
		}
		path = "fail.jsp";
		return "fail";
	}
}

add.jsp中的代码(添加商品):

<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>添加页面</title>
<script src="SpryAssets/SpryValidationTextField.js" type="text/javascript"></script>
<link href="SpryAssets/SpryValidationTextField.css" rel="stylesheet" type="text/css" />
</head>

<body>
<div align="center"></div>
<form id="form1" name="form1" method="post" action="add_Product.action">
  <table width="466" border="1" align="center">
    <tr>
      <td colspan="2"><div align="center">
        <p>添加商品 </p>
      </div></td>
    </tr>
    <tr>
      <td width="151"><div align="center">商品名称</div></td>
      <td width="299"><div align="center">
        <label for="textfield"></label>
        <span id="sprytextfield1">
        <input type="text" name="pd.pname" id="pd.pname" />
        <span class="textfieldRequiredMsg">需要提供一个值。</span></span></div></td>
    </tr>
    <tr>
      <td><div align="center">商品数量</div></td>
      <td><label for="textfield2"></label>
        <div align="left"><span id="sprytextfield3">
          <input type="text" name="pd.num" id="pd.num" />
        <span class="textfieldRequiredMsg">需要提供一个值。</span><span class="textfieldInvalidFormatMsg">格式无效。</span></span></div></td>
    </tr>
    <tr>
      <td><div align="center">商品单价</div></td>
      <td><label for="textfield3"></label>
        <div align="left"><span id="sprytextfield2">
          <input type="text" name="pd.price" id="pd.price" />
        <span class="textfieldRequiredMsg">需要提供一个值。</span><span class="textfieldInvalidFormatMsg">格式无效。</span></span></div></td>
    </tr>
    <tr>
      <td colspan="2"><div align="center">
        <input type="submit" name="button" id="button" value="提交" />
        <input type="reset" name="button2" id="button2" value="重置" />
      </div>        
      <div align="center"></div></td>
    </tr>
  </table>
</form>
<script type="text/javascript">
var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1");
var sprytextfield3 = new Spry.Widget.ValidationTextField("sprytextfield3", "integer");
var sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2", "currency");
</script>
</body>
</html>

list.jsp中的代码:

<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>商品列表</title>
</head>

<body>
<p align="center">显示商品</p>
<hr width="770" />
<table width="700" border="1" align="center">
  <tr>
    <td><div align="center">序号</div></td>
    <td><div align="center">品名</div></td>
    <td><div align="center">价格</div></td>
    <td><div align="center">数量</div></td>
    <td><div align="center">小计</div></td>
    <td><div align="center">操作</div></td>
  </tr>
  <c:forEach items="${list}" var="pd" varStatus="vs">
  <tr align="center">
    <td>${vs.index+1}</td>
    <td>${pd.pname}</td>
    <td>${pd.price}</td>
    <td>${pd.num}</td>
    <td>${pd.count}</td>
    <td><a href="delByIndex_Product.action?index=${vs.index}">删除</a> <a href="findByIndex_Product.action?index=${vs.index}">修改</a></td>
  </tr>
  </c:forEach>
</table>
<p align="center"><a href="add.jsp">返回添加</a></p>
<hr width="770" />
<p>&nbsp;</p>
</body>
</html>

update.jsp中的代码:

<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>修改页面</title>
<script src="SpryAssets/SpryValidationTextField.js" type="text/javascript"></script>
<link href="SpryAssets/SpryValidationTextField.css" rel="stylesheet" type="text/css" />
</head>

<body>
<div align="center"></div>
<form id="form1" name="form1" method="post" action="update_Product.action">
  <table width="466" border="1" align="center">
    <tr>
      <td colspan="2"><div align="center">
        <p>添加商品 </p>
      </div></td>
    </tr>
    <tr>
      <td width="151"><div align="center">商品名称</div></td>
      <td width="299"><div align="center">
        <label for="textfield"></label>
        <span id="sprytextfield1">
        <input type="text" name="pd.pname" id="pd.pname" value="${oldPd.pname}"/>
        <input type="hidden" name="pd.pid" id="pd.pid" value="${oldPd.pid}"/>
        <span class="textfieldRequiredMsg">需要提供一个值。</span></span></div></td>
    </tr>
    <tr>
      <td><div align="center">商品数量</div></td>
      <td><label for="textfield2"></label>
        <div align="left"><span id="sprytextfield3">
          <input type="text" name="pd.num" id="pd.num" value="${oldPd.num}"/>
        <span class="textfieldRequiredMsg">需要提供一个值。</span><span class="textfieldInvalidFormatMsg">格式无效。</span></span></div></td>
    </tr>
    <tr>
      <td><div align="center">商品单价</div></td>
      <td><label for="textfield3"></label>
        <div align="left"><span id="sprytextfield2">
          <input type="text" name="pd.price" id="pd.price" value="${oldPd.price}"/>
        <span class="textfieldRequiredMsg">需要提供一个值。</span><span class="textfieldInvalidFormatMsg">格式无效。</span></span></div></td>
    </tr>
    <tr>
      <td colspan="2"><div align="center">
        <input type="submit" name="button" id="button" value="提交" />
        <input type="reset" name="button2" id="button2" value="重置" />
      </div>        
      <div align="center"></div></td>
    </tr>
  </table>
</form>
<script type="text/javascript">
var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1");
var sprytextfield3 = new Spry.Widget.ValidationTextField("sprytextfield3", "integer");
var sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2", "currency");
</script>
</body>
</html>

fail.jsp中的代码:

<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>错误页面</title>
</head>

<body>
操作错误,请返回<a href="add.jsp">添加页面</a>
</body>
</html>

运行结果展示:
在这里插入图片描述
在这里插入图片描述
自己刚开始运营公众号啦,本人目前就职于某bank,感兴趣的可关注我的公众号,欢迎交流!
在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/96915.html

(1)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!