JavaWeb基础
servlet案例学习——应用MVC架构实现项目
基础知识回顾
Model1
JavaBean(业务逻辑层)+JSP(显示层),JavaBean与数据库交互,JSP接受浏览器的请求并作出响应。
Model2
MVC思想的体现
JSP(V)给控制层Servlet(C)提交请求,Servlet调用模型层JavaBean(M),JavaBean读取数据库,并将结果返回给Servlet,最后呈现JSP页面。
项目概述
MVC模型实现(JSP+Servlet+DAO)
- 创建购物车类
- 编写Servlet
- 创建页面层
项目实现
1.创建DBHelper类
jdbc连接数据库模板。
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBHelper {
private static final String driver = "com.mysql.jdbc.Driver";
private static final String url = "jdbc:mysql://localhost:3306/shopping?useUnicode=yes&characterEncoding=UTF-8";
private static final String username = "root";
private static final String password = "";
private static Connection conn = null;
public static Connection getConnection() {
try {
Class.forName(driver);
if (conn == null) {
conn = DriverManager.getConnection(url, username, password);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
2.创建数据库
jdbc连接mysql,创建shopping表。
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for items
-- ----------------------------
DROP TABLE IF EXISTS `items`;
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;
-- ----------------------------
-- Records of items
-- ----------------------------
INSERT INTO `items` VALUES ('1', '沃特篮球鞋', '佛山', '180', '500', '001.jpg');
INSERT INTO `items` VALUES ('2', '安踏运动鞋', '福州', '120', '800', '002.jpg');
INSERT INTO `items` VALUES ('3', '耐克运动鞋', '广州', '500', '1000', '003.jpg');
INSERT INTO `items` VALUES ('4', '阿迪达斯T血衫', '上海', '388', '600', '004.jpg');
INSERT INTO `items` VALUES ('5', '李宁文化衫', '广州', '180', '900', '005.jpg');
INSERT INTO `items` VALUES ('6', '小米3', '北京', '1999', '3000', '006.jpg');
INSERT INTO `items` VALUES ('7', '小米2S', '北京', '1299', '1000', '007.jpg');
INSERT INTO `items` VALUES ('8', 'thinkpad笔记本', '北京', '6999', '500', '008.jpg');
INSERT INTO `items` VALUES ('9', 'dell笔记本', '北京', '3999', '500', '009.jpg');
INSERT INTO `items` VALUES ('10', 'ipad5', '北京', '5999', '500', '010.jpg');
3.创建商品类Items
package entity;
//商品类
public class Items {
private int id; // 商品编号
private String name; // 商品名称
private String city; // 产地
private int price; // 价格
private int number; // 库存
private String picture; // 商品图片
// 保留此不带参数的构造方法
public Items() {
}
public Items(int id, String name, String city, int price, int number, String picture) {
this.id = id;
this.name = name;
this.city = city;
this.picture = picture;
this.price = price;
this.number = number;
}
// getter setter方法
@Override
public int hashCode() {
// 相同商品的名称和id都相同,所以hashcode也相同
return this.getId() + this.getName().hashCode();
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
if (this == obj) {
return true;
}
if (obj instanceof Items) {
Items i = (Items) obj;
if (this.getId() == i.getId() && this.getName().equals(i.getName())) {
return true;
} else {
return false;
}
} else {
return false;
}
}
public String toString() {
return "商品编号:" + this.getId() + ",商品名称:" + this.getName();
}
}
4.业务逻辑类
获得所有商品信息以及每个商品具体信息,同时使用cookie技术实现最近5条商品信息的记录。
代码中体现了对于数据库的基本操作,包括语句PreparedStatement和数据集Resultset的使用。
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import util.DBHelper;
import entity.Items;
//商品的业务逻辑类
public class ItemsDAO {
// 获得所有的商品信息
public ArrayList<Items> getAllItems() {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
ArrayList<Items> list = new ArrayList<Items>(); // 商品集合
try {
conn = DBHelper.getConnection();
String sql = "select * from items;"; // SQL语句
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
while (rs.next()) {
Items item = new Items();
item.setId(rs.getInt("id"));
item.setName(rs.getString("name"));
item.setCity(rs.getString("city"));
item.setNumber(rs.getInt("number"));
item.setPrice(rs.getInt("price"));
item.setPicture(rs.getString("picture"));
list.add(item);// 把一个商品加入集合
}
return list; // 返回集合。
} catch (Exception ex) {
ex.printStackTrace();
return null;
} finally {
// 释放数据集对象
if (rs != null) {
try {
rs.close();
rs = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
// 释放语句对象
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
// 根据商品编号获得商品资料
public Items getItemsById(int id) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = DBHelper.getConnection();
String sql = "select * from items where id=?;"; // SQL语句
stmt = conn.prepareStatement(sql);
stmt.setInt(1, id);
rs = stmt.executeQuery();
if (rs.next()) {
Items item = new Items();
item.setId(rs.getInt("id"));
item.setName(rs.getString("name"));
item.setCity(rs.getString("city"));
item.setNumber(rs.getInt("number"));
item.setPrice(rs.getInt("price"));
item.setPicture(rs.getString("picture"));
return item;
} else {
return null;
}
} catch (Exception ex) {
ex.printStackTrace();
return null;
} finally {
// 释放数据集对象
if (rs != null) {
try {
rs.close();
rs = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
// 释放语句对象
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
//获取最近浏览的前五条商品信息
public ArrayList<Items> getViewList(String list)
{
System.out.println("list:"+list);
ArrayList<Items> itemlist = new ArrayList<Items>();
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(getItemsById(Integer.parseInt(arr[i])));
}
}
else
{
for(int i=arr.length-1;i>=0;i--)
{
itemlist.add(getItemsById(Integer.parseInt(arr[i])));
}
}
return itemlist;
}
else
{
return null;
}
}
}
5.购物车类
添加、删除、计算价格,在entity实体层中添加购物车类。
-
使用HashMap,商品对象Items为key,商品数量为value。获得键的集合使用set。
-
添加、删除、计算价格的方法中包含对集合的基本操作。
-
对购物车类进行测试。Set<Map.Entry<Items, Integer>>表示一个Map对象(包含键值对)的Set集合。
-
打印出来的信息可以通过在实体类Items中重写toString方法实现。
package entity;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
//购物车类
public class Cart {
// 购买商品的集合
private HashMap<Items, Integer> goods;
// 购物车的总金额
private double totalPrice;
// 构造方法
public Cart() {
goods = new HashMap<Items, Integer>();
totalPrice = 0.0;
}
public HashMap<Items, Integer> getGoods() {
return goods;
}
public void setGoods(HashMap<Items, Integer> goods) {
this.goods = goods;
}
public double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(double totalPrice) {
this.totalPrice = totalPrice;
}
// 添加商品进购物车的方法
public boolean addGoodsInCart(Items item, int number) {
if (goods.containsKey(item)) {
goods.put(item, goods.get(item) + number);
} else {
goods.put(item, number);
}
calTotalPrice(); // 重新计算购物车的总金额
return true;
}
// 删除商品的方法
public boolean removeGoodsFromCart(Items item) {
goods.remove(item);
calTotalPrice(); // 重新计算购物车的总金额
return true;
}
// 统计购物车的总金额
public double calTotalPrice() {
double sum = 0.0;
Set<Items> keys = goods.keySet(); // 获得键的集合
Iterator<Items> it = keys.iterator(); // 获得迭代器对象
while (it.hasNext()) {
Items i = it.next();
sum += i.getPrice() * goods.get(i);
}
this.setTotalPrice(sum); // 设置购物车的总金额
return this.getTotalPrice();
}
public static void main(String[] args) {
// 先创建两个商品对象
Items i1 = new Items(1, "沃特篮球鞋", "温州", 200, 500, "001.jpg");
Items i2 = new Items(2, "李宁运动鞋", "广州", 300, 500, "002.jpg");
Items i3 = new Items(1, "沃特篮球鞋", "温州", 200, 500, "001.jpg");
Cart c = new Cart();
c.addGoodsInCart(i1, 1);
c.addGoodsInCart(i2, 2);
// 再次购买沃特篮球鞋,购买3双
c.addGoodsInCart(i3, 3);
// 遍历购物商品的集合
Set<Map.Entry<Items, Integer>> items = c.getGoods().entrySet();
for (Map.Entry<Items, Integer> obj : items) {
System.out.println(obj);
}
System.out.println("购物车的总金额:" + c.getTotalPrice());
}
}
6.保证不添加重复商品进购物车
new出的对象一定是不同的,所以需要对同一个商品进行操作时,为了保证是同一个对象操作,要重写hashcode和equals方法。如果两个对象的id和name都相同,那么必然为同一个商品,hashcode也相同,并且equals方法返回true。
@Override
public int hashCode() {
// 相同商品的名称和id都相同,所以hashcode也相同
return this.getId() + this.getName().hashCode();
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
if (this == obj) {
return true;
}
if (obj instanceof Items) {
Items i = (Items) obj;
if (this.getId() == i.getId() && this.getName().equals(i.getName())) {
return true;
} else {
return false;
}
} else {
return false;
}
}
7.编写jsp页面层
包括index.jsp、detail.jsp、success.jsp、failure.jsp、cart.jsp。
detail.jsp
- 在detail.jsp中,将直接跳转jsp改为通过servlet进行处理。href="servlet/CartServlet?action=show
- JavaScript代码用于显示一个模态窗口。
<script 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%>/servlet/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>
<style type="text/css">
hr{
border-color:FF7F00;
}
div{
float:left;
margin-left: 30px;
margin-right:30px;
margin-top: 5px;
margin-bottom: 5px;
}
div dd{
margin:0px;
font-size:10pt;
}
div dd.dd_name
{
color:blue;
}
div dd.dd_city
{
color:#000;
}
div #cart
{
margin:0px auto;
text-align:right;
}
span{
padding:0 2px;border:1px #c0c0c0 solid;cursor:pointer;
}
a{
text-decoration: none;
}
</style>
</head>
<body>
<h1>商品详情</h1>
<a href="index.jsp">首页</a> >> <a href="index.jsp">商品列表</a>
<hr>
<center>
<table width="750" height="60" cellpadding="0" cellspacing="0" border="0">
<tr>
<!-- 商品详情 -->
<%
ItemsDAO itemDao = new ItemsDAO();
Items item = itemDao.getItemsById(Integer.parseInt(request.getParameter("id")));
if(item!=null)
{
%>
<td width="70%" valign="top">
<table>
<tr>
<td rowspan="5"><img src="images/<%=item.getPicture()%>" width="200" height="160"/></td>
</tr>
<tr>
<td><B><%=item.getName() %></B></td>
</tr>
<tr>
<td>产地:<%=item.getCity()%></td>
</tr>
<tr>
<td>价格:<%=item.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(<%=item.getId()%>)"><img src="images/in_cart.png"></a><a href="servlet/CartServlet?action=show"><img src="images/view_cart.jpg"/></a>
</div>
</td>
<%
}
%>
<%
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<Items> itemlist = itemDao.getViewList(list);
if(itemlist!=null&&itemlist.size()>0 )
{
System.out.println("itemlist.size="+itemlist.size());
for(Items i:itemlist)
{
%>
<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>
<%
}
}
%>
<!-- 循环结束 -->
</td>
</tr>
</table>
</center>
</body>
</html>
cart.jsp
- 实现show方法。判断session中是否存在cart对象,如果存在就显示出商品信息。再通过JavaScript实现了增加减少的功能。
- 实现delete方法。
<script language="javascript">
function delcfm() {
if (!confirm("确认要删除?")) {
window.event.returnValue = false;
}
}
</script>
</head>
<body>
<h1>我的购物车</h1>
<a href="index.jsp">首页</a> >> <a href="index.jsp">商品列表</a>
<hr>
<div id="shopping">
<form action="" method="">
<table>
<tr>
<th>商品名称</th>
<th>商品单价</th>
<th>商品价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
<%
//首先判断session中是否有购物车对象
if(request.getSession().getAttribute("cart")!=null)
{
%>
<!-- 循环的开始 -->
<%
Cart cart = (Cart)request.getSession().getAttribute("cart");
HashMap<Items,Integer> goods = cart.getGoods();
Set<Items> items = goods.keySet();
Iterator<Items> it = items.iterator();
while(it.hasNext())
{
Items i = it.next();
%>
<tr name="products" id="product_id_1">
<td class="thumb"><img src="images/<%=i.getPicture()%>" /><a href=""><%=i.getName()%></a></td>
<td class="number"><%=i.getPrice() %></td>
<td class="price" id="price_id_1">
<span><%=i.getPrice()*goods.get(i) %></span>
<input type="hidden" value="" />
</td>
<td class="number">
<%=goods.get(i)%>
</td>
<td class="delete">
<a href="servlet/CartServlet?action=delete&id=<%=i.getId()%>" onclick="delcfm();">删除</a>
</td>
</tr>
<%
}
%>
<!--循环的结束-->
</table>
<div class="total"><span id="total">总计:<%=cart.getTotalPrice() %>¥</span></div>
<%
}
%>
<div class="button"><input type="submit" value="" /></div>
</form>
</div>
</body>
</html>
8.编写servlet,添加商品进购物车
- action的动作分为add,show,delete。在每个动作中实现对应逻辑,并调转到相应的jsp页面。该步骤可以使用struts等的配置。
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.ItemsDAO;
import entity.Cart;
import entity.Items;
public class CartServlet extends HttpServlet {
private String action; // 表示购物车的动作 ,add,show,delete
// 商品业务逻辑类的对象
private ItemsDAO idao = new ItemsDAO();
/**
* Constructor of the object.
*/
public CartServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
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")) // 如果是添加商品进购物车
{
if (addToCart(request, response)) {
request.getRequestDispatcher("/success.jsp").forward(request, response);
} else {
request.getRequestDispatcher("/failure.jsp").forward(request, response);
}
}
if (action.equals("show"))// 如果是显示购物车
{
request.getRequestDispatcher("/cart.jsp").forward(request, response);
}
if (action.equals("delete")) // 如果是执行删除购物车中的商品
{
if (deleteFromCart(request, response)) {
request.getRequestDispatcher("/cart.jsp").forward(request, response);
} else {
request.getRequestDispatcher("/cart.jsp").forward(request, response);
}
}
}
}
// 添加商品进购物车的方法
private boolean addToCart(HttpServletRequest request, HttpServletResponse response) {
String id = request.getParameter("id");
String number = request.getParameter("num");
Items item = idao.getItemsById(Integer.parseInt(id));
// 是否是第一次给购物车添加商品,需要给session中创建一个新的购物车对象
if (request.getSession().getAttribute("cart") == null) {
Cart cart = new Cart();
request.getSession().setAttribute("cart", cart);
}
Cart cart = (Cart) request.getSession().getAttribute("cart");
if (cart.addGoodsInCart(item, 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");
Items item = idao.getItemsById(Integer.parseInt(id));
if (cart.removeGoodsFromCart(item)) {
return true;
} else {
return false;
}
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}