基于javaweb+mysql的jsp+servlet仿天猫网上商城项目(java+jsp+servlet+mysql+ajax)
运行环境
Java≥8、MySQL≥5.7、Tomcat≥8
开发工具
eclipse/idea/myeclipse/sts等均可配置运行
适用
课程设计,大作业,毕业设计,项目练习,学习演示等
功能说明
基于javaweb+mysql的JSP+Servlet仿天猫网上商城项目(java+jsp+servlet+mysql+ajax)
一、项目简述
功能:
前台:
-
用户模块
-
分类模块
-
商品模块
-
购物车模块
-
订单模块
后台:
-
管理员模块
-
分类管理模块
-
商品管理模块
-
订单模块
二、项目运行
环境配置: Jdk1.8 + Tomcat8.5 + mysql + Eclispe (IntelliJ IDEA,Eclispe,MyEclispe,Sts 都支持)
项目技术: JSP + C3P0+ Servlert + html+ css + JavaScript + JQuery + Ajax + Fileupload等等。
public String update(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了Product update方法");
Map<String, String> params = new HashMap<>();
InputStream inputStream = super.parseUpload(request, params);
int cid = Integer.parseInt(params.get("cid"));
Category c = categoryDAO.get(cid);
int id = Integer.parseInt(params.get("id"));
String name = params.get("name");
String subTitle = params.get("subTitle");
float originalPrice = Float.parseFloat(params.get("originalPrice"));
float promotePrice = Float.parseFloat(params.get("promotePrice"));
int stock = Integer.parseInt(params.get("stock"));
Product p = new Product();
p.setId(id);
p.setName(name);
p.setSubTitle(subTitle);
p.setOriginalPrice(originalPrice);
p.setPromotePrice(promotePrice);
p.setStock(stock);
p.setCategory(c);
p.setCreateDate(new Date());
productDAO.update(p);
return "@admin_product_list?cid=" + p.getCategory().getId();
}
@Override
public String edit(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了Product edit方法");
int id =Integer.parseInt(request.getParameter("id"));
Product p = productDAO.get(id);
request.setAttribute("p",p);
return "admin/editProduct.jsp";
}
public String updatePropertyValue(HttpServletRequest request, HttpServletResponse response, Page page){
System.out.println("调用了Product updatePropertyValue方法");
int pvid = Integer.parseInt(request.getParameter("pvid"));
String value = request.getParameter("value");
PropertyValue pv = propertyValueDAO.get(pvid);
pv.setValue(value);
propertyValueDAO.update(pv);
return "%success";
}
resp.getWriter().print(redirect.substring(1));
} else {
req.getRequestDispatcher(redirect).forward(req, resp);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
public InputStream parseUpload(HttpServletRequest request, Map<String, String> params){
InputStream is = null;
try{
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
//设置上传的文件大小限制为10M
factory.setSizeThreshold(1024 * 1024);
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while(iter.hasNext()){
FileItem item = (FileItem) iter.next();
if(!item.isFormField()){
//获取上传文件的输入流
is = item.getInputStream();
} else {
String paramName = item.getFieldName();
String paramValue = item.getString();
paramValue = new String(paramValue.getBytes("ISO-8859-1"), "UTF-8");
params.put(paramName, paramValue);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
}
package servlet;
float total = 0;
for (String strid : oiids) {
int oiid = Integer.parseInt(strid);
OrderItem oi = orderItemDAO.get(oiid);
total += oi.getProduct().getPromotePrice() * oi.getNumber();
ois.add(oi);
}
request.getSession().setAttribute("ois", ois);
request.setAttribute("total", total);
return "buy.jsp";
}
/**
* 购物车
*
* @param request
* @param response
* @param page
* @return
*/
public String cart(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了ForeServlet cart方法");
User user = (User) request.getSession().getAttribute("user");
List<OrderItem> ois = orderItemDAO.listByUser(user.getId());
request.setAttribute("ois", ois);
return "cart.jsp";
}
/**
* 加入购物车
*
* @param request
* @param response
* @param page
* @return
*/
public String addCart(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了ForeServlet addCart方法");
int pid = Integer.parseInt(request.getParameter("pid"));
int num = Integer.parseInt(request.getParameter("num"));
Product p = productDAO.get(pid);
System.out.println(user.getName());
System.out.println(user.getPassword());
userDAO.add(user);
return "@registerSuccess.jsp";
}
/**
* 登录
*
* @param request
* @param response
* @param page
* @return
*/
public String login(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了 ForeServlet login方法");
Map<String, String> params = new HashMap<>();
InputStream inputStream = super.parseUpload(request, params);
System.out.println(params);
String name = params.get("name");
String password = params.get("password");
// 登录
User user = userDAO.get(name, password);
if (null == user) {
request.setAttribute("msg", "账号密码错误");
return "login.jsp";
}
// 将账号密码储存在Session中
request.getSession().setAttribute("user", user);
return "@forehome";
}
/**
* 登出
*
* @param request
* @param response
* @param page
* @return
*/
} catch (FileUploadException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
}
package servlet;
public class PropertyServlet extends BaseBackServlet {
@Override
public String add(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了Property add方法");
Map<String,String> params = new HashMap<>();
InputStream is = super.parseUpload(request, params);
System.out.println(params);
int cid = Integer.parseInt(params.get("cid"));
Category c = categoryDAO.get(cid);
String name = params.get("name");
System.out.println(name);
Property p = new Property();
p.setCategory(c);
p.setName(name);
}
}
package servlet;
public class CategoryServlet extends BaseBackServlet {
@Override
public String add(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了category add方法");
Map<String,String> params = new HashMap<>();
InputStream is = super.parseUpload(request, params);
System.out.println(params);
String name = params.get("name");
Category c = new Category();
c.setName(name);
categoryDAO.add(c);
File imageFolder = new File(request.getSession().getServletContext().getRealPath("img/category"));
File file = new File(imageFolder, c.getId() + ".jpg");
try{
if(null != is && 0 != is.available()){
try(
public abstract class BaseBackServlet extends HttpServlet {
/* 添加 */
public abstract String add(HttpServletRequest request, HttpServletResponse response, Page page);
/* 删除 */
public abstract String delete(HttpServletRequest request, HttpServletResponse response, Page page);
/* 更新 */
public abstract String update(HttpServletRequest request, HttpServletResponse response, Page page);
/* 修改 */
public abstract String edit(HttpServletRequest request, HttpServletResponse response, Page page);
/* 显示 */
public abstract String list(HttpServletRequest request, HttpServletResponse response, Page page);
protected CategoryDAO categoryDAO = new CategoryDAO();
protected OrderDAO orderDAO = new OrderDAO();
protected OrderItemDAO orderItemDAO = new OrderItemDAO();
protected ProductDAO productDAO = new ProductDAO();
protected ProductImageDAO productImageDAO = new ProductImageDAO();
protected PropertyDAO propertyDAO = new PropertyDAO();
protected PropertyValueDAO propertyValueDAO = new PropertyValueDAO();
protected ReviewDAO reviewDAO = new ReviewDAO();
protected UserDAO userDAO = new UserDAO();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try{
/* 获取分页信息 */
int start = 0;
int count = 5;
try{
start = Integer.parseInt(req.getParameter("page.start"));
count = Integer.parseInt(req.getParameter("page.count"));
/* 借助反射,调用对应的方法 */
String method = (String)req.getAttribute("method");
Method m = this.getClass().getMethod(method, HttpServletRequest.class, HttpServletResponse.class, Page.class);
String redirect = m.invoke(this, req, resp, page).toString();
/* 根据方法的返回值,进行相应的客户端、服务端跳转,或仅输出字符串 */
if(redirect.startsWith("@")){
resp.sendRedirect(redirect.substring(1));
} else if(redirect.startsWith("%")){
resp.getWriter().print(redirect.substring(1));
} else {
req.getRequestDispatcher(redirect).forward(req, resp);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
public InputStream parseUpload(HttpServletRequest request, Map<String, String> params){
InputStream is = null;
try{
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
//设置上传的文件大小限制为10M
factory.setSizeThreshold(1024 * 1024);
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while(iter.hasNext()){
FileItem item = (FileItem) iter.next();
if(!item.isFormField()){
//获取上传文件的输入流
is = item.getInputStream();
} else {
}
@Override
public String delete(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了Product delete方法");
int id = Integer.parseInt(request.getParameter("id"));
Product p = productDAO.get(id);
productDAO.delete(id);
return "@admin_product_list?cid=" + p.getCategory().getId();
}
@Override
public String update(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了Product update方法");
Map<String, String> params = new HashMap<>();
InputStream inputStream = super.parseUpload(request, params);
int cid = Integer.parseInt(params.get("cid"));
Category c = categoryDAO.get(cid);
int id = Integer.parseInt(params.get("id"));
String name = params.get("name");
String subTitle = params.get("subTitle");
float originalPrice = Float.parseFloat(params.get("originalPrice"));
float promotePrice = Float.parseFloat(params.get("promotePrice"));
int stock = Integer.parseInt(params.get("stock"));
Product p = new Product();
p.setId(id);
p.setName(name);
p.setSubTitle(subTitle);
p.setOriginalPrice(originalPrice);
p.setPromotePrice(promotePrice);
p.setStock(stock);
p.setCategory(c);
p.setCreateDate(new Date());
productDAO.update(p);
return "@admin_product_list?cid=" + p.getCategory().getId();
}
@Override
public String edit(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了Product edit方法");
String name = params.get("name");
String subTitle = params.get("subTitle");
float originalPrice = Float.parseFloat(params.get("originalPrice"));
float promotePrice = Float.parseFloat(params.get("promotePrice"));
int stock = Integer.parseInt(params.get("stock"));
Product p = new Product();
p.setId(id);
p.setName(name);
p.setSubTitle(subTitle);
p.setOriginalPrice(originalPrice);
p.setPromotePrice(promotePrice);
p.setStock(stock);
p.setCategory(c);
p.setCreateDate(new Date());
productDAO.update(p);
return "@admin_product_list?cid=" + p.getCategory().getId();
}
@Override
public String edit(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了Product edit方法");
int id =Integer.parseInt(request.getParameter("id"));
Product p = productDAO.get(id);
request.setAttribute("p",p);
return "admin/editProduct.jsp";
}
public String updatePropertyValue(HttpServletRequest request, HttpServletResponse response, Page page){
System.out.println("调用了Product updatePropertyValue方法");
int pvid = Integer.parseInt(request.getParameter("pvid"));
String value = request.getParameter("value");
PropertyValue pv = propertyValueDAO.get(pvid);
pv.setValue(value);
propertyValueDAO.update(pv);
return "%success";
}
public String editPropertyValue(HttpServletRequest request, HttpServletResponse response, Page page){
System.out.println("调用了Product editPropertyValue方法");
return "%fail";
}
/**
* 模态登录框通过 Ajax 方法登录
*
* @param request
* @param response
* @param page
* @return
*/
public String loginAjax(HttpServletRequest request, HttpServletResponse response, Page page) {
String name = request.getParameter("name");
String password = request.getParameter("password");
User user = userDAO.get(name, password);
if (user == null)
return "%fail";
request.getSession().setAttribute("user", user);
return "%success";
}
/**
* 显示产品页
*
* @param request
* @param response
* @param page
* @return
*/
public String product(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了 ForeServlet product方法");
int pid = Integer.parseInt(request.getParameter("pid"));
Product p = productDAO.get(pid);
// 获取产品的single图片和detail图片
List<ProductImage> productSingleImages = productImageDAO.list(p, ProductImageDAO.type_single);
List<ProductImage> productDetailImages = productImageDAO.list(p, ProductImageDAO.type_detail);
p.setProductSingleImages(productSingleImages);
p.setProductDetailImages(productDetailImages);
//p.setFirstProductImage(productSingleImages.get(0));
// 获取产品属性信息
List<PropertyValue> pvs = propertyValueDAO.list(p.getId());
oi.setUser(user);
oi.setProduct(p);
oi.setNumber(num);
orderItemDAO.add(oi);
oiid = oi.getId();
}
return "@forebuy?oiid=" + oiid;
}
/**
* 结算页面
*
* @param request
* @param response
* @param page
* @return
*/
public String buy(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了ForeServlet buy方法");
String[] oiids = request.getParameterValues("oiid");
List<OrderItem> ois = new ArrayList<>();
float total = 0;
for (String strid : oiids) {
int oiid = Integer.parseInt(strid);
OrderItem oi = orderItemDAO.get(oiid);
total += oi.getProduct().getPromotePrice() * oi.getNumber();
ois.add(oi);
}
request.getSession().setAttribute("ois", ois);
request.setAttribute("total", total);
return "buy.jsp";
}
/**
* 购物车
*
* @param request
* @param response
* @param page
* @return
public class PropertyServlet extends BaseBackServlet {
@Override
public String add(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了Property add方法");
Map<String,String> params = new HashMap<>();
InputStream is = super.parseUpload(request, params);
System.out.println(params);
int cid = Integer.parseInt(params.get("cid"));
Category c = categoryDAO.get(cid);
String name = params.get("name");
System.out.println(name);
Property p = new Property();
p.setCategory(c);
p.setName(name);
propertyDAO.add(p);
return "@admin_property_list?cid=" + p.getCategory().getId();
}
@Override
public String delete(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了Property delete方法");
int id = Integer.parseInt(request.getParameter("id"));
Property p = propertyDAO.get(id);
propertyDAO.delete(id);
return "@admin_property_list?cid=" + p.getCategory().getId();
}
@Override
public String update(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了Property update方法");
Map<String,String> params = new HashMap<>();
InputStream is = super.parseUpload(request, params);
System.out.println(params);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
public InputStream parseUpload(HttpServletRequest request, Map<String, String> params){
InputStream is = null;
try{
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
//设置上传的文件大小限制为10M
factory.setSizeThreshold(1024 * 1024);
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while(iter.hasNext()){
FileItem item = (FileItem) iter.next();
if(!item.isFormField()){
//获取上传文件的输入流
is = item.getInputStream();
} else {
String paramName = item.getFieldName();
String paramValue = item.getString();
paramValue = new String(paramValue.getBytes("ISO-8859-1"), "UTF-8");
params.put(paramName, paramValue);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
//获取上传文件的输入流
is = item.getInputStream();
} else {
String paramName = item.getFieldName();
String paramValue = item.getString();
paramValue = new String(paramValue.getBytes("ISO-8859-1"), "UTF-8");
params.put(paramName, paramValue);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
}
package servlet;
public class PropertyServlet extends BaseBackServlet {
@Override
public String add(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了Property add方法");
Map<String,String> params = new HashMap<>();
InputStream is = super.parseUpload(request, params);
System.out.println(params);
int cid = Integer.parseInt(params.get("cid"));
Category c = categoryDAO.get(cid);
String name = params.get("name");
System.out.println(name);
package servlet;
public class UserServlet extends BaseBackServlet {
@Override
public String add(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了 UserServlet add方法");
return null;
}
@Override
public String delete(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了 UserServlet delete方法");
int id = Integer.parseInt(request.getParameter("id"));
userDAO.delete(id);
return "@admin_user_list";
}
@Override
public String update(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了 UserServlet update方法");
Map<String, String> params = new HashMap<>();
InputStream is = super.parseUpload(request, params);
System.out.println(params);
int id = Integer.parseInt(params.get("id"));
String password = params.get("password");
public class CategoryServlet extends BaseBackServlet {
@Override
public String add(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了category add方法");
Map<String,String> params = new HashMap<>();
InputStream is = super.parseUpload(request, params);
System.out.println(params);
String name = params.get("name");
Category c = new Category();
c.setName(name);
categoryDAO.add(c);
File imageFolder = new File(request.getSession().getServletContext().getRealPath("img/category"));
File file = new File(imageFolder, c.getId() + ".jpg");
try{
if(null != is && 0 != is.available()){
try(
FileOutputStream fos = new FileOutputStream(file);
){
byte[] b = new byte[1024 * 1024];
int length = 0;
while(-1 != (length = is.read(b))){
fos.write(b, 0, length);
}
fos.flush();
//通过以下代码,将文件保存为jsp格式
BufferedImage img = ImageUtil.change2jpg(file);
ImageIO.write(img, "jpg", file);
Map<String, String> params = new HashMap<>();
InputStream inputStream = super.parseUpload(request, params);
System.out.println(params);
String name = params.get("name");
String password = params.get("password");
System.out.println(name);
// 判断用户名是否存在
boolean exist = userDAO.isExists(name);
if (exist) {
request.setAttribute("msg", "用户名已经被使用");
return "register.jsp";
}
User user = new User();
user.setName(name);
user.setPassword(password);
System.out.println(user.getName());
System.out.println(user.getPassword());
userDAO.add(user);
return "@registerSuccess.jsp";
}
/**
* 登录
*
* @param request
* @param response
* @param page
* @return
*/
public String login(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了 ForeServlet login方法");
Map<String, String> params = new HashMap<>();
InputStream inputStream = super.parseUpload(request, params);
System.out.println(params);
String name = params.get("name");
String password = params.get("password");
c.setName(name);
c.setId(id);
categoryDAO.update(c);
File imageFolder = new File(request.getSession().getServletContext().getRealPath("img/category"));
File file = new File(imageFolder, c.getId() + ".jpg");
try{
if(null != is && 0 != is.available()){
try(
FileOutputStream fos = new FileOutputStream(file);
){
byte[] b = new byte[1024 * 1024];
int length = 0;
while(-1 != (length = is.read(b))){
fos.write(b, 0, length);
}
fos.flush();
//通过以下代码,将文件保存为jsp格式
BufferedImage img = ImageUtil.change2jpg(file);
ImageIO.write(img, "jpg", file);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return "@admin_category_list";
}
@Override
public String edit(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了category edit方法");
int id = Integer.parseInt(request.getParameter("id"));
Category category = categoryDAO.get(id);
request.setAttribute("c", category);
return "admin/editCategory.jsp";
}
@Override
public String list(HttpServletRequest request, HttpServletResponse response, Page page) {
List<Category> cs = categoryDAO.list(page.getStart(), page.getCount());
int total = categoryDAO.getTotal();
page.setTotal(total);
request.setAttribute("thecs", cs);
"register",
"loginAjax",
"login",
"product",
"category",
"search"};
String uri = request.getRequestURI();
uri = StringUtils.remove(uri, contextPath);
if (uri.startsWith("/fore") && !uri.startsWith("/foreServlet")) {
String method = StringUtils.substringAfterLast(uri, "/fore");
if (!Arrays.asList(noNeedAuthPage).contains(method)) {
User user = (User) request.getSession().getAttribute("user");
if (null == user) {
response.sendRedirect("login.jsp");
return;
}
}
}
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
package filter;
public class BackServletFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
* @param response
* @param page
* @return
*/
public String loginAjax(HttpServletRequest request, HttpServletResponse response, Page page) {
String name = request.getParameter("name");
String password = request.getParameter("password");
User user = userDAO.get(name, password);
if (user == null)
return "%fail";
request.getSession().setAttribute("user", user);
return "%success";
}
/**
* 显示产品页
*
* @param request
* @param response
* @param page
* @return
*/
public String product(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了 ForeServlet product方法");
int pid = Integer.parseInt(request.getParameter("pid"));
Product p = productDAO.get(pid);
// 获取产品的single图片和detail图片
List<ProductImage> productSingleImages = productImageDAO.list(p, ProductImageDAO.type_single);
List<ProductImage> productDetailImages = productImageDAO.list(p, ProductImageDAO.type_detail);
p.setProductSingleImages(productSingleImages);
p.setProductDetailImages(productDetailImages);
//p.setFirstProductImage(productSingleImages.get(0));
// 获取产品属性信息
List<PropertyValue> pvs = propertyValueDAO.list(p.getId());
// 获取产品评价信息
List<Review> reviews = reviewDAO.list(p.getId());
// 设置产品销量数和评价数
productDAO.setSaleAndReviewNumber(p);
request.setAttribute("p", p);
}
/**
* 支付完成界面
* @param request
* @param response
* @param page
* @return
*/
public String payed(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了ForeServlet payed方法");
int oid = Integer.parseInt(request.getParameter("oid"));
Order order = orderDAO.get(oid);
order.setStatus(OrderDAO.waitDelivery);
order.setPayDate(new Date());
orderDAO.update(order);
request.setAttribute("o", order);
return "payed.jsp";
}
/**
* 我的订单页面
* @param request
* @param response
* @param page
* @return
*/
public String bought(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了ForeServlet bought方法");
User user = (User) request.getSession().getAttribute("user");
List<Order> os = orderDAO.list(user.getId(), OrderDAO.delete);
orderItemDAO.fill(os);
request.setAttribute("os", os);
return "bought.jsp";
}
}
package servlet;
String method = (String)req.getAttribute("method");
Method m = this.getClass().getMethod(method, HttpServletRequest.class, HttpServletResponse.class, Page.class);
String redirect = m.invoke(this, req, resp, page).toString();
/* 根据方法的返回值,进行相应的客户端、服务端跳转,或仅输出字符串 */
if(redirect.startsWith("@")){
resp.sendRedirect(redirect.substring(1));
} else if(redirect.startsWith("%")){
resp.getWriter().print(redirect.substring(1));
} else {
req.getRequestDispatcher(redirect).forward(req, resp);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
public InputStream parseUpload(HttpServletRequest request, Map<String, String> params){
InputStream is = null;
try{
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
//设置上传的文件大小限制为10M
factory.setSizeThreshold(1024 * 1024);
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while(iter.hasNext()){
FileItem item = (FileItem) iter.next();
if(!item.isFormField()){
//获取上传文件的输入流
is = item.getInputStream();
} else {
String paramName = item.getFieldName();
String paramValue = item.getString();
paramValue = new String(paramValue.getBytes("ISO-8859-1"), "UTF-8");
params.put(paramName, paramValue);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
public String list(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了 ProductImageServlet list方法");
int pid = Integer.parseInt(request.getParameter("pid"));
Product p = productDAO.get(pid);
List<ProductImage> pisSingle = productImageDAO.list(p, ProductImageDAO.type_single);
List<ProductImage> pisDetail = productImageDAO.list(p, ProductImageDAO.type_detail);
request.setAttribute("p", p);
request.setAttribute("pisSingle", pisSingle);
request.setAttribute("pisDetail", pisDetail);
return "admin/listProductImage.jsp";
}
}
package servlet;
public class ProductServlet extends BaseBackServlet {
@Override
public String add(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了Product add方法");
Map<String, String> params = new HashMap<>();
InputStream inputStream = super.parseUpload(request, params);
System.out.println(params);
int cid = Integer.parseInt(params.get("cid"));
Category c = categoryDAO.get(cid);
public class BaseForeServlet extends HttpServlet {
protected CategoryDAO categoryDAO = new CategoryDAO();
protected OrderDAO orderDAO = new OrderDAO();
protected OrderItemDAO orderItemDAO = new OrderItemDAO();
protected ProductDAO productDAO = new ProductDAO();
protected ProductImageDAO productImageDAO = new ProductImageDAO();
protected PropertyDAO propertyDAO = new PropertyDAO();
protected PropertyValueDAO propertyValueDAO = new PropertyValueDAO();
protected UserDAO userDAO = new UserDAO();
protected ReviewDAO reviewDAO = new ReviewDAO();
@Override
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try{
// 初始化分页信息
int start = 0;
int count = 10;
try{
// start = Integer.parseInt(req.getParameter("page.start"));
// count = Integer.parseInt(req.getParameter("page.count"));
} catch (Exception e) {
e.printStackTrace();
}
Page page = new Page(start, count);
String method = (String) req.getAttribute("method");
// 借助反射,调用对应的方法
Method m = this.getClass().getMethod(method, HttpServletRequest.class, HttpServletResponse.class, Page.class);
String redirect = m.invoke(this, req, resp, page).toString();
// 根据反射后的结果,执行相应的操作
if(redirect.startsWith("@")) {
resp.sendRedirect(redirect.substring(1));
} else if(redirect.startsWith("%")) {
resp.getWriter().print(redirect.substring(1));
} else {
req.getRequestDispatcher(redirect).forward(req, resp);
}
return "%fail";
}
/**
* 模态登录框通过 Ajax 方法登录
*
* @param request
* @param response
* @param page
* @return
*/
public String loginAjax(HttpServletRequest request, HttpServletResponse response, Page page) {
String name = request.getParameter("name");
String password = request.getParameter("password");
User user = userDAO.get(name, password);
if (user == null)
return "%fail";
request.getSession().setAttribute("user", user);
return "%success";
}
/**
* 显示产品页
*
* @param request
* @param response
* @param page
* @return
*/
public String product(HttpServletRequest request, HttpServletResponse response, Page page) {
System.out.println("调用了 ForeServlet product方法");
int pid = Integer.parseInt(request.getParameter("pid"));
Product p = productDAO.get(pid);
// 获取产品的single图片和detail图片
List<ProductImage> productSingleImages = productImageDAO.list(p, ProductImageDAO.type_single);
List<ProductImage> productDetailImages = productImageDAO.list(p, ProductImageDAO.type_detail);
p.setProductSingleImages(productSingleImages);
p.setProductDetailImages(productDetailImages);
//p.setFirstProductImage(productSingleImages.get(0));
// 获取产品属性信息
List<PropertyValue> pvs = propertyValueDAO.list(p.getId());
// 获取产品评价信息
List<Review> reviews = reviewDAO.list(p.getId());
// 设置产品销量数和评价数
productDAO.setSaleAndReviewNumber(p);