概念
本文讲解和实现网上蛋糕商城的后台管理系统中的商品管理功能。
商品列表
点击后台管理系统的head.jsp头部的"商品管理"功能选项,向服务器发送请求/admin/goods_list
因此需要在servlet包中创建AdminGoodsListServlet类,用于获取商品信息列表
java
package servlet;
import model.Page;
import service.GoodsService;
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 java.io.IOException;
@WebServlet(name = "admin_goods_list",urlPatterns = "/admin/goods_list")
public class AdminGoodsListServlet extends HttpServlet {
private GoodsService gService = new GoodsService();
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int type = 0;//推荐类型
if(request.getParameter("type") != null) {
type=Integer.parseInt(request.getParameter("type") ) ;
}
int pageNumber = 1;
if(request.getParameter("pageNumber") != null) {
try {
pageNumber=Integer.parseInt(request.getParameter("pageNumber") ) ;
}
catch (Exception e)
{
}
}
if(pageNumber<=0)
pageNumber=1;
Page p = gService.getGoodsRecommendPage(type, pageNumber);
if(p.getTotalPage()==0)
{
p.setTotalPage(1);
p.setPageNumber(1);
}
else {
if(pageNumber>=p.getTotalPage()+1)
{
p = gService.getGoodsRecommendPage(type, pageNumber);
}
}
request.setAttribute("p", p);
request.setAttribute("type", type);
request.getRequestDispatcher("/admin/goods_list.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
以上代码中,接收浏览器请求,并判断浏览器是否传递了分类参数,商品分类为条幅,热销,新品等,如果没有传递分类参数,则默认获取所有商品信息,并分页显示,将参数传递给业务逻辑层,这里功能已经实现了,则不再重复赘述。最后将查询的数据显示在goods_list.jsp页面上
html
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<title>商品列表</title>
<meta charset="utf-8"/>
<link rel="stylesheet" href="css/bootstrap.css"/>
</head>
<body>
<div class="container-fluid">
<jsp:include page="/admin/header.jsp"></jsp:include>
<div class="text-right"><a class="btn btn-warning" href="/admin/goods_add.jsp">添加商品</a></div>
<br>
<ul role="tablist" class="nav nav-tabs">
<li <c:if test="${type==0 }">class="active"</c:if> role="presentation"><a href="/admin/goods_list">全部商品</a></li>
<li <c:if test="${type==1 }">class="active"</c:if> role="presentation"><a href="/admin/goods_list?type=1">条幅推荐</a></li>
<li <c:if test="${type==2 }">class="active"</c:if> role="presentation"><a href="/admin/goods_list?type=2">热销推荐</a></li>
<li <c:if test="${type==3 }">class="active"</c:if> role="presentation"><a href="/admin/goods_list?type=3">新品推荐</a></li>
</ul>
<br>
<table class="table table-bordered table-hover">
<tr>
<th width="5%">ID</th>
<th width="10%">图片</th>
<th width="10%">名称</th>
<th width="20%">介绍</th>
<th width="10%">价格</th>
<th width="10%">类目</th>
<th width="25%">操作</th>
</tr>
<c:forEach items="${p.list }" var="g">
<tr>
<td><p>${g.id }</p></td>
<td><p><a href="/goods_detail?id=${g.id}" target="_blank"><img src="${g.cover}" width="100px" height="100px"></a></p></td>
<td><p><a href="/goods_detail?id=${g.id}" target="_blank">${g.name}</a></p></td>
<td><p>${g.intro}</p></td>
<td><p>${g.price}</p></td>
<td><p>${g.type.name}</p></td>
<td>
<p>
<c:choose>
<c:when test="${g.isScroll }">
<a class="btn btn-info" href="/admin/goods_recommend?id=${g.id }&method=remove&typeTarget=1&pageNumber=${p.pageNumber}&type=${type}">移出条幅</a>
</c:when>
<c:otherwise>
<a class="btn btn-primary" href="/admin/goods_recommend?id=${g.id }&method=add&typeTarget=1&pageNumber=${p.pageNumber}&type=${type}">加入条幅</a>
</c:otherwise>
</c:choose>
<c:choose>
<c:when test="${g.isHot }">
<a class="btn btn-info" href="/admin/goods_recommend?id=${g.id }&method=remove&typeTarget=2&pageNumber=${p.pageNumber}&type=${type}">移出热销</a>
</c:when>
<c:otherwise>
<a class="btn btn-primary" href="/admin/goods_recommend?id=${g.id }&method=add&typeTarget=2&pageNumber=${p.pageNumber}&type=${type}">加入热销</a>
</c:otherwise>
</c:choose>
<c:choose>
<c:when test="${g.isNew }">
<a class="btn btn-info" href="/admin/goods_recommend?id=${g.id }&method=remove&typeTarget=3&pageNumber=${p.pageNumber}&type=${type}">移出新品</a>
</c:when>
<c:otherwise>
<a class="btn btn-primary" href="/admin/goods_recommend?id=${g.id }&method=add&typeTarget=3&pageNumber=${p.pageNumber}&type=${type}">加入新品</a>
</c:otherwise>
</c:choose>
</p>
<a class="btn btn-success" href="/admin/goods_editshow?id=${g.id }& pageNumber=${p.pageNumber}&type=${type}">修改</a>
<a class="btn btn-danger" href="/admin/goods_delete?id=${g.id }&pageNumber=${p.pageNumber}&type=${type}">删除</a>
</td>
</tr>
</c:forEach>
</table>
<br>
<jsp:include page="/page.jsp">
<jsp:param value="/admin/goods_list" name="url"/>
<jsp:param value="&type=${type }" name="param"/>
</jsp:include>
<br>
</div>
</body>
</html>
以上页面代码中,通过分支语句判断每一个商品的类型来区分该商品是加入还是移出的按钮文本信息。
当用户点击条幅推荐,热销推荐,新品推荐时,则还是向以上服务器地址发送请求,只不过这里需要携带分类参数。
加入移出分类
每一个商品都有可能加入条幅,热销,新品等分类,加入的了商品也有可能移出条幅,热销和新品分类,没有任何一个商品永久性的进行促销活动,因此每一个商品都有可能进行加入某一个分类或者移出某一个分类。
这里当点击加入或者移出条幅,热销和新品分类时,向服务器发送请求地址/admin/goods_recommend,并携带商品编号,页码,加入还是移出参数,分类参数等等
因此需要在servlet包中创建AdminGoodsRecommendServlet类,完成以上功能
java
package servlet;
import service.GoodsService;
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 java.io.IOException;
@WebServlet(name = "admin_goods_recommend",urlPatterns = "/admin/goods_recommend")
public class AdminGoodsRecommendServlet extends HttpServlet {
private GoodsService gService = new GoodsService();
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
String method = request.getParameter("method");
int typeTarget=Integer.parseInt(request.getParameter("typeTarget"));
if(method.equals("add")) {
gService.addRecommend(id, typeTarget);
}else {
gService.removeRecommend(id, typeTarget);
}
request.getRequestDispatcher("/admin/goods_list").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
以上代码中,根据浏览器传递的method参数是add还是remove还区分是加入分类还是移出分类操作,这里需要将参数信息发送给业务逻辑层执行
java
//将某个商品分类添加至标识
public void addRecommend(int id,int type) {
try {
gDao.addRecommend(id, type);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//将某个商品删除标识
public void removeRecommend(int id,int type) {
try {
gDao.removeRecommend(id, type);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
接着业务逻辑层将执行的参数传递给数据访问层执行
java
public void addRecommend(int id,int type) throws SQLException {
QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "insert into recommend(type,goods_id) values(?,?)";
r.update(sql,type,id);
}
public void removeRecommend(int id,int type) throws SQLException {
QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "delete from recommend where type=? and goods_id=?";
r.update(sql,type,id);
}
最后,执行成功后,刷新商品列表页面,同步执行后的结果显示在页面上。
添加新商品
点击商品列表页面中的"添加商品"按钮,跳转至goods_add.jsp页面
html
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<title>商品添加</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="css/bootstrap.css" />
</head>
<body>
<div class="container-fluid">
<jsp:include page="/admin/header.jsp"></jsp:include>
<br><br>
<form class="form-horizontal" action="/admin/goods_add" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="input_name" class="col-sm-1 control-label">名称</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="input_name" name="name" required="required">
</div>
</div>
<div class="form-group">
<label for="input_name" class="col-sm-1 control-label">价格</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="input_name" name="price" >
</div>
</div>
<div class="form-group">
<label for="input_name" class="col-sm-1 control-label">介绍</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="input_name" name="intro" >
</div>
</div>
<div class="form-group">
<label for="input_name" class="col-sm-1 control-label">库存</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="input_name" name="stock" >
</div>
</div>
<div class="form-group">
<label for="input_file" class="col-sm-1 control-label">封面图片</label>
<div class="col-sm-6">
<input type="file" name="cover" id="input_file" required="required">推荐尺寸: 500 * 500
</div>
</div>
<div class="form-group">
<label for="input_file" class="col-sm-1 control-label">详情图片1</label>
<div class="col-sm-6">
<input type="file" name="image1" id="input_file" required="required">推荐尺寸: 500 * 500
</div>
</div>
<div class="form-group">
<label for="input_file" class="col-sm-1 control-label">详情图片2</label>
<div class="col-sm-6">
<input type="file" name="image2" id="input_file" required="required">推荐尺寸: 500 * 500
</div>
</div>
<div class="form-group">
<label for="select_topic" class="col-sm-1 control-label">类目</label>
<div class="col-sm-6">
<select class="form-control" id="select_topic" name="typeid">
<c:forEach items="${typeList }" var="t">
<option value="${t.id }">${t.name }</option>
</c:forEach>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<button type="submit" class="btn btn-success">提交保存</button>
</div>
</div>
</form>
</div>
</body>
</html>
当管理员填写商品信息并上传商品图片后,点击"提交保存"按钮,将所有信息提交给服务器/admin/goods_add
因此需要在servlet包中创建AdminGoodsAddServlet类
java
package servlet;
import model.Goods;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import service.GoodsService;
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 java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
@WebServlet(name = "admin_goods_add",urlPatterns = "/admin/goods_add")
public class AdminGoodsAddServlet extends HttpServlet {
private GoodsService gService = new GoodsService();
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> list = upload.parseRequest(request);
Goods g = new Goods();
for(FileItem item:list) {
if(item.isFormField()) {
switch(item.getFieldName()) {
case "name":
g.setName(item.getString("utf-8"));
break;
case "price":
g.setPrice(Integer.parseInt(item.getString("utf-8")));
break;
case "intro":
g.setIntro(item.getString("utf-8"));
break;
case "stock":
g.setStock(Integer.parseInt(item.getString("utf-8")));
break;
case "typeid":
g.setTypeid(Integer.parseInt(item.getString("utf-8")));
break;
}
}else {
if(item.getInputStream().available()<=0)continue;
String fileName = item.getName();
fileName = fileName.substring(fileName.lastIndexOf("."));
fileName = "/"+new Date().getTime()+fileName;
String path = this.getServletContext().getRealPath("/picture")+fileName;
InputStream in = item.getInputStream();
FileOutputStream out = new FileOutputStream(path);
byte[] buffer = new byte[1024];
int len=0;
while( (len=in.read(buffer))>0 ) {
out.write(buffer);
}
in.close();
out.close();
item.delete();
switch(item.getFieldName()) {
case "cover":
g.setCover("/picture"+fileName);
break;
case "image1":
g.setImage1("/picture"+fileName);
break;
case "image2":
g.setImage2("/picture"+fileName);
break;
}
}
}
gService.insert(g);
request.getRequestDispatcher("/admin/goods_list").forward(request, response);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
以上代码中,接收新商品的所有信息,通过request请求对象获得所有表单属性,并通过分支语句区分不同的表单数据,对上传的图片做单独的处理,使用当前的实时时间拼接图片名称作为图片的新名称,并将上传的图片指定存储在项目资源的picture文件夹中,接着将商品信息封装在goods对象中,发送给业务逻辑层执行
java
//添加新商品信息
public void insert(Goods goods) {
try {
gDao.insert(goods);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
接着,传递给数据访问层执行
java
public void insert(Goods g) throws SQLException {
QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "insert into goods(name,cover,image1,image2,price,intro,stock,type_id) values(?,?,?,?,?,?,?,?)";
r.update(sql,g.getName(),g.getCover(),g.getImage1(),g.getImage2(),g.getPrice(),g.getIntro(),g.getStock(),g.getType().getId());
}
最后,添加成功后,返回商品列表页面。
修改商品信息
在商品列表页面中,选择要修改的商品中的"修改"按钮,向服务器发送请求地址/admin/goods_editshow,并携带商品编号,页码以及分类参数
因此需要在servlet包中创建AdminGoodsEditshowServelt类
java
package servlet;
import model.Goods;
import service.GoodsService;
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 java.io.IOException;
@WebServlet(name = "admin_goods_editshow",urlPatterns = "/admin/goods_editshow")
public class AdminGoodsEditshowServelt extends HttpServlet {
private GoodsService gService = new GoodsService();
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
Goods g = gService.getGoodsById(id);
request.setAttribute("g", g);
request.getRequestDispatcher("/admin/goods_edit.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
以上代码中,接收浏览器要修改的商品编号作为查询条件,将要修改的商品的信息从数据库中查询出来并显示在goods_edit.jsp修改页面上
html
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<title>商品编辑</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="css/bootstrap.css" />
</head>
<body>
<div class="container-fluid">
<jsp:include page="/admin/header.jsp"></jsp:include>
<br><br>
<form class="form-horizontal" action="/admin/goods_edit" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="${g.id }"/>
<input type="hidden" name="cover" value="${g.cover }"/>
<input type="hidden" name="image1" value="${g.image1 }"/>
<input type="hidden" name="image2" value="${g.image2 }"/>
<input type="hidden" name="pageNo" value="${param.pageNo }"/>
<input type="hidden" name="type" value="${param.type }"/>
<div class="form-group">
<label for="input_name" class="col-sm-1 control-label">名称</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="input_name" name="name" value="${g.name }" required="required">
</div>
</div>
<div class="form-group">
<label for="input_name" class="col-sm-1 control-label">价格</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="input_name" name="price" value="${g.price }">
</div>
</div>
<div class="form-group">
<label for="input_name" class="col-sm-1 control-label">介绍</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="input_name" name="intro" value="${g.intro }">
</div>
</div>
<div class="form-group">
<label for="input_name" class="col-sm-1 control-label">库存</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="input_name" name="stock" value="${g.stock }">
</div>
</div>
<div class="form-group">
<label for="input_file" class="col-sm-1 control-label">封面图片</label>
<div class="col-sm-6"><img src="${pageContext.request.contextPath }${g.cover }" width="100" height="100"/>
<input type="file" name="cover" id="input_file">推荐尺寸: 500 * 500
</div>
</div>
<div class="form-group">
<label for="input_file" class="col-sm-1 control-label">详情图片1</label>
<div class="col-sm-6"><img src="${pageContext.request.contextPath }${g.image1 }" width="100" height="100"/>
<input type="file" name="image1" id="input_file">推荐尺寸: 500 * 500
</div>
</div>
<div class="form-group">
<label for="input_file" class="col-sm-1 control-label">详情图片2</label>
<div class="col-sm-6"><img src="${pageContext.request.contextPath }${g.image2 }" width="100" height="100"/>
<input type="file" name="image2" id="input_file">推荐尺寸: 500 * 500
</div>
</div>
<div class="form-group">
<label for="select_topic" class="col-sm-1 control-label">类目</label>
<div class="col-sm-6">
<select class="form-control" id="select_topic" name="typeid">
<c:forEach items="${typeList }" var="t">
<option <c:if test="${t.id==g.type.id }">selected="selected"</c:if> value="${t.id }">${t.name }</option>
</c:forEach>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<button type="submit" class="btn btn-success">提交修改</button>
</div>
</div>
</form>
</div>
</body>
</html>
当管理员在该页面上修改了商品信息后,将更新后的商品信息提交给服务器地址/admin/goods_edit
因此需要在servlet包中创建AdminGoodsEditServlet类
java
package servlet;
import model.Goods;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import service.GoodsService;
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 java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
@WebServlet(name = "admin_goods_edit",urlPatterns = "/admin/goods_edit")
public class AdminGoodsEditServlet extends HttpServlet {
private GoodsService gService = new GoodsService();
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> list = upload.parseRequest(request);
Goods g = new Goods();
int pageNumber =1;
int type=0;
for(FileItem item:list) {
if(item.isFormField()) {
switch(item.getFieldName()) {
case "id":
g.setId(Integer.parseInt(item.getString("utf-8")));
break;
case "name":
g.setName(item.getString("utf-8"));
break;
case "price":
g.setPrice(Float.parseFloat(item.getString("utf-8")));
break;
case "intro":
g.setIntro(item.getString("utf-8"));
break;
case "cover":
g.setCover(item.getString("utf-8"));
break;
case "image1":
g.setImage1(item.getString("utf-8"));
break;
case "image2":
g.setImage2(item.getString("utf-8"));
break;
case "stock":
g.setStock(Integer.parseInt(item.getString("utf-8")));
break;
case "typeid":
g.setTypeid(Integer.parseInt(item.getString("utf-8")));
break;
case "pageNumber":
pageNumber=Integer.parseInt(item.getString("utf-8"));
break;
case "type":
type = Integer.parseInt(item.getString("utf-8"));
break;
}
}else {
if(item.getInputStream().available()<=0)continue;
String fileName = item.getName();
fileName = fileName.substring(fileName.lastIndexOf("."));
fileName = "/"+new Date().getTime()+fileName;
String path = this.getServletContext().getRealPath("/picture")+fileName;
InputStream in = item.getInputStream();
FileOutputStream out = new FileOutputStream(path);
byte[] buffer = new byte[1024];
int len=0;
while( (len=in.read(buffer))>0 ) {
out.write(buffer);
}
in.close();
out.close();
item.delete();
switch(item.getFieldName()) {
case "cover":
g.setCover("/picture"+fileName);
break;
case "image1":
g.setImage1("/picture"+fileName);
break;
case "image2":
g.setImage2("/picture"+fileName);
break;
}
}
}
gService.update(g);
request.getRequestDispatcher("/admin/goods_list?pageNumber="+pageNumber+"&type="+type).forward(request, response);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
以上代码中,所执行的代码基本和添加新商品的代码执行功能类似,只是该功能不是添加至数据库,而是修改已存在的商品信息。
java
//修改商品信息
public void update(Goods goods) {
try {
gDao.update(goods);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
接着,将更新的商品信息同步至数据库中
java
public void update(Goods g) throws SQLException {
QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "update goods set name=?,cover=?,image1=?,image2=?,price=?,intro=?,stock=?,type_id=? where id=?";
r.update(sql,g.getName(),g.getCover(),g.getImage1(),g.getImage2(),g.getPrice(),g.getIntro(),g.getStock(),g.getType().getId(),g.getId());
}
最后,返回商品列表页面同步刷新商品信息。
删除商品
在商品列表页面中,选择要删除的商品中的"删除"按钮,向服务器发送请求/admin/goods_delete
因此需要在servlet包中创建AdminGoodsDeleteServlet类
java
package servlet;
import service.GoodsService;
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 java.io.IOException;
@WebServlet(name = "admin_goods_delete",urlPatterns = "/admin/goods_delete")
public class AdminGoodsDeleteServlet extends HttpServlet {
private GoodsService gService = new GoodsService();
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
gService.delete(id);
request.getRequestDispatcher("/admin/goods_list").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
以上代码中,接收浏览器发送的商品编号,发送给业务逻辑层执行,删除成功后刷新商品列表页面
java
//根据id删除商品信息
public void delete(int id) {
try {
gDao.delete(id);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
接着传递给数据访问层执行
java
public void delete(int id) throws SQLException {
QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "delete from goods where id = ?";
r.update(sql,id);
}
最后,刷新商品列表页面。
到此,本项目所有功能讲解完毕,该项目还有很大的功能扩充和代码优化的空间,读者可以自行优化和更新该项目的功能。