Java进阶-案例训练(十七)(商城项目(2))

文章目录

  • 一、登录权限校验
  • 二、七天内自动登录(分两步走)
    • 2.1 第一步(存放到cookie中)
    • 2.2 第二步(再次登录用户名密码还在输入框)
  • 三、权限修改
  • 四、批量删除
  • 五、分类分页查询
  • 六、分类-添加分类
  • 七、分类--修改分类
    • 7.1 跳转并回显
    • 7.2 修改并保存
  • 八、分类--分类删除

一、登录权限校验

Java进阶-案例训练(十七)(商城项目(2))_第1张图片
在filter包中创建LoginFilter.java


package com.zql.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import com.zql.pojo.User;

/**

* author:Daniel

* version:1.0

*/

@WebFilter("/*")
public class LoginFilter implements Filter{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		HttpServletRequest req = (HttpServletRequest) request;
		//获取请求路径
		String uri = req.getRequestURI();
		//System.out.println(uri);  ///xiaomi/admin/login.jsp
		//要放行的路径
		if(uri.contains("/login.jsp") || uri.contains("/user") || uri.contains("/css/")
				|| uri.contains("/img/") || uri.contains("images") || uri.contains("/js/")) {
			
			chain.doFilter(request, response);
			return;
		}
		//判断用户是否存在
		User user = (User) req.getSession().getAttribute("user");
		if(user != null) {
			//放行
			chain.doFilter(request, response);
		}else {
			//友好提示
			req.setAttribute("msg", "兄台,请先登录后再使用~~");
			//转发到登录页面
			request.getRequestDispatcher("/admin/login.jsp").forward(request, response);
		}
	}
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
	}
}

最终显示:http://localhost:8080/xiaomi/admin/main.jsp

Java进阶-案例训练(十七)(商城项目(2))_第2张图片

二、七天内自动登录(分两步走)

2.1 第一步(存放到cookie中)

(1) 在admin/login.jsp 中修改 “忘记密码”为“自动登录”如下

设置为1的目的是,当为“1”时,就是自动登录
在这里插入图片描述
(2)在原先基础上编写UserServlet代码:
Java进阶-案例训练(十七)(商城项目(2))_第3张图片

//七天自动登录
	String AutoLogin = request.getParameter("AutoLogin");
	
	if("1".equals(AutoLogin)) {
		//创建Cookie
		Cookie cookie  = new Cookie("autoLogin",user.getUsername()+"@"+user.getPassword());
		//创建生存时间 设置7天时间
		cookie.setMaxAge(7*24*60*60);
		//添加到cookie中
		response.addCookie(cookie);	
	}else {
		Cookie cookie  = new Cookie("autoLogin","");
		cookie.setMaxAge(0);
		response.addCookie(cookie);	
	}

最终显示:

(1)通过debug调试(已经存到了cookie中)

Java进阶-案例训练(十七)(商城项目(2))_第4张图片

(2)浏览器F12查看(也已经存到了cookie中)

Java进阶-案例训练(十七)(商城项目(2))_第5张图片

2.2 第二步(再次登录用户名密码还在输入框)

AutoFilter.java


package com.zql.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.zql.pojo.User;
import com.zql.service.UserService;
import com.zql.service.impl.UserServiceImpl;

/**

* author:Daniel

* version:1.0

*/

public class AutoFilter implements Filter{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		//将上层接口中的request转成子接口HttpServletRequest中的req
		HttpServletRequest req = (HttpServletRequest) request;
		
		//从session获取user对象(登陆成功)
		User aotoUser = (User) req.getSession().getAttribute("user");
		if(aotoUser !=null) {
			chain.doFilter(request, response);
			return;
		}
		try {
		//1.获取存在Cookie中的用户名和密码
		Cookie[] cookies = req.getCookies();
		//2.判断cookies是否为空
		Cookie aotoLogin = null;
		if(cookies != null) {
			//遍历cookies
			for (Cookie cookie : cookies) {
				//判断cookies中的哪个是我想要的
				if("autoLogin".equals(cookies)) {
					
					aotoLogin = cookie;
					//结束遍历
					break;
				}
			}
		}
		if(aotoLogin == null) {
			chain.doFilter(request, response);
			return;
		}
		//aotoLogin不等于空  获取用户名和密码进行登录
		String[] value = aotoLogin.getValue().split("@");
		String username = value[0];
		String password = value[1];
		//业务处理
		UserService us = new UserServiceImpl();
		
		User user = us.adminLogin(username, password);
		
		if(user != null) {
			
			req.getSession().setAttribute("user", user);
		}
		chain.doFilter(request, response);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub	
	}
}

最终显示(退出后依然存在用户名和密码)

Java进阶-案例训练(十七)(商城项目(2))_第6张图片

三、权限修改

(1)修改admin/user_list.jsp

<td>			       	
	<c:if test="${p.manager == 0}">
	      <a href="${pageContext.request.contextPath }/user?method=updateRole&manager=1&uid=${p.uid}">指定管理员</a>
	</c:if>
	<c:if test="${p.manager == 1}">
	      <a href="${pageContext.request.contextPath }/user?method=updateRole&manager=0&uid=${p.uid}"><font color='red'>撤销管理员</font></a>
	</c:if>
</td>

(2)UserServlet.java

//权限修改
		public String updateRole(HttpServletRequest request, HttpServletResponse response)throws Exception {
			//处理数据
			String manager = request.getParameter("manager");
			String uid = request.getParameter("uid");
			User user = us.updateRole(manager,uid);
			//重定向
			response.sendRedirect(request.getContextPath()+"/user?method=findUserByPageBean&pageNumber=1");
			return null;
		}

(3)UserService.java

	//权限修改
	User updateRole(String manager, String uid) throws Exception;

(4)UserServiceImpl.java

	//权限修改
	@Override
	public User updateRole(String manager, String uid)throws Exception {
		
		return ud.updateRole(manager,uid) ;
	}

(5) UserDao.java

	//权限修改
	User updateRole(String manager, String uid) throws Exception;

(6)UserDaoImpl.java

	//权限修改
	@Override
	public User updateRole(String manager, String uid) throws Exception {
		String sql = "update user set manager =? where uid = ?";
		Object[] param = {manager,uid};
		qr.update(sql, param);
		return null;
	}	

最后显示:

Java进阶-案例训练(十七)(商城项目(2))_第7张图片

四、批量删除

(1)在user_list.jsp中添加 ${p.uid}
Java进阶-案例训练(十七)(商城项目(2))_第8张图片
(2)编写 admin/user_list.jsp

<!-- 批量删除 -->
	<script type="text/javascript">
		/*页面加载 */
		$(function() {
			/* 批量选择 */
			$("#checkbox_main").click(function(){
				
				//alert(111)
				//获得批量框的值
				var temp = $("#checkbox_main").prop("checked");
				
				$("[name=ids]").prop("checked",temp);/*批量选择 */
				
			});
			
			/* 批量删除 */
			$("#batchDelete").click(function(){
				//alert(22)
				var ids = "";
				$("[name=ids]:checked").each(function(){
					ids += ","+this.value;
				})
				//alert(ids)
				ids = ids.substring(1);//去掉前面的一个逗号
				//alert(ids.substring(1));
				//传入后台进行删除
				location.href="${pageContext.request.contextPath}/user?method=batchDelete&ids="+ids;
			})	
		})
	</script>

UserServlet.java

//批量删除 batchDelete
		public String batchDelete(HttpServletRequest request, HttpServletResponse response)throws Exception {
			//处理数据
			String ids = request.getParameter("ids");
			System.out.println(ids);
			us.batchDelete(ids);
			//重定向
			response.sendRedirect(request.getContextPath()+"/user?method=findUserByPageBean&pageNumber=1");
			return null;
		}

UserService.java

//批量删除
void batchDelete(String ids) throws Exception;

UserServiceImpl.java

//进行批量删除
	@Override
	public void batchDelete(String ids) throws Exception {
		ud.batchDelete(ids);
	}	

UserDao.java

//进行批量删除
	void batchDelete(String ids)throws Exception;

UserDaoImpl.java

//进行批量删除
	@Override
	public void batchDelete(String ids) throws Exception {
		String sql = "delete from user where uid in ("+ ids +")";
		qr.update(sql);
	}

Java进阶-案例训练(十七)(商城项目(2))_第9张图片

五、分类分页查询

(1)导入表 (文件三) : sql:

CREATE TABLE `category` (
  `cid` INT(10) PRIMARY KEY AUTO_INCREMENT,
  `cname` VARCHAR(50) NOT NULL,
  `state` INT(1) DEFAULT NULL,
  `order_number` INT(5) DEFAULT NULL,
  `description` VARCHAR(100) DEFAULT NULL,
  `create_time` DATETIME
);

INSERT  INTO `category`(`cid`,`cname`,`state`,`order_number`,`description`,`create_time`) VALUES 
(2,'航天系列',1,1,'卫星、航母火箭等','2021-12-25 09:53:55'),(3,'手机 平板',1,0,'各种小米系手机','2021-12-25 14:20:12'),
(4,'家电',1,2,' 电视、冰箱、洗衣机等','2021-12-25 14:20:42'),(5,'儿童玩具',1,3,'各种玩具','2021-12-25 16:38:14'),
(6,'智能产品',1,2,'','2021-12-26 14:46:27'),(7,'图书 内容',1,55,'','2021-12-25 09:53:55'),
(8,'移动电源 电池 插线板',1,33,'1','2018-12-26 14:48:16'),(9,'耳机 音响',1,34,'','2021-12-26 14:48:31'),
(10,'保护套 贴膜',1,35,'','2021-12-26 14:48:47'),(11,'线材 支架 存储卡',1,36,'','2021-12-26 14:49:04'),
(12,'箱包 服饰 鞋 眼镜',1,37,'','2021-12-26 14:49:19'),(13,'米兔 生活周边',1,38,'','2021-12-26 14:49:33');

(2)创建结构(类)

Java进阶-案例训练(十七)(商城项目(2))_第10张图片
(3)根据导入的category表编写javabean
Category.java


package com.zql.pojo;

import java.io.Serializable;

/**

* author:Daniel

* version:1.0

*/

public class Category implements Serializable{
	
	private int cid;//序号
	private String cname;//类别名称
	private int state;//启动状态 1 启用  0 未启用
	private int order_number;//排序序号
	private String description;//描述
	private String create_time;//创建时间
	public Category() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Category(int cid, String cname, int state, int order_number, String description, String create_time) {
		super();
		this.cid = cid;
		this.cname = cname;
		this.state = state;
		this.order_number = order_number;
		this.description = description;
		this.create_time = create_time;
	}
	public int getCid() {
		return cid;
	}
	public void setCid(int cid) {
		this.cid = cid;
	}
	public String getCname() {
		return cname;
	}
	public void setCname(String cname) {
		this.cname = cname;
	}
	public int getState() {
		return state;
	}
	public void setState(int state) {
		this.state = state;
	}
	public int getOrder_number() {
		return order_number;
	}
	public void setOrder_number(int order_number) {
		this.order_number = order_number;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public String getCreate_time() {
		return create_time;
	}
	public void setCreate_time(String create_time) {
		this.create_time = create_time;
	}
	@Override
	public String toString() {
		return "Category [cid=" + cid + ", cname=" + cname + ", state=" + state + ", order_number=" + order_number
				+ ", description=" + description + ", create_time=" + create_time + "]";
	}
}

(4) 起名 方法(入口)
admin/left.jsp

在这里插入图片描述

${pageContext.request.contextPath }/category?method=categoryByPageBean&pageNumber=1

(5) CategoryServlet.java


package com.zql.web.servlet;

import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zql.pojo.Category;
import com.zql.pojo.User;
import com.zql.service.CategoryService;
import com.zql.service.impl.CategoryServiceImpl;
import com.zql.utils.PageBean;

/**

* author:Daniel

* version:1.0

*/
@WebServlet("/category")
public class CategoryServlet extends BaseServlet{
	
	private CategoryService cs = new CategoryServiceImpl();
		
	//对查询的类别进行分页
	public String categoryByPageBean(HttpServletRequest request, HttpServletResponse response)throws Exception {
		//处理数据
		String pageNumber = request.getParameter("pageNumber");
		//创建pageBean对象
		PageBean pb = new PageBean();
		//设置当前页
		pb.setPageNumber(Integer.parseInt(pageNumber));
		//设置每页显示的条数
		pb.setPageSize(5);
		PageBean<Category> pageBean = cs.categoryByPageBean(pb);
		
		//System.out.println(pageBean);
		//存放到域中
		request.setAttribute("pb", pageBean);
		//请求转发
		return "/admin/category_list.jsp";
	}
	
	
	//查询所有类别
	public String findCategoryList(HttpServletRequest request, HttpServletResponse response)throws Exception {
		
		//处理数据
		String parameter = request.getParameter("");
		List<Category> clist = cs.findCategoryList();
		
		//System.out.println(clist);//控制台测试查询出来了
		//存放到域中
		request.setAttribute("clist", clist);
		
		return "/admin/category_list.jsp";
	}
}

(6) CategoryServicejava


package com.zql.service;

import java.sql.SQLException;
import java.util.List;

import com.zql.pojo.Category;
import com.zql.utils.PageBean;

/**

* author:Daniel

* version:1.0

*/

public interface CategoryService {

	//对查询的类别进行分页
	PageBean<Category> categoryByPageBean(PageBean pb) throws SQLException;

	//查询所有商品类别
	List<Category> findCategoryList() throws SQLException;
}

(7)CategoryServiceImpl.java


package com.zql.service.impl;

import java.sql.SQLException;
import java.util.List;

import com.zql.dao.CategoryDao;
import com.zql.dao.impl.CategoryDaoImpl;
import com.zql.pojo.Category;
import com.zql.pojo.User;
import com.zql.service.CategoryService;
import com.zql.utils.PageBean;

/**

* author:Daniel

* version:1.0

*/

public class CategoryServiceImpl implements CategoryService{
	
	private CategoryDao cd = new CategoryDaoImpl();

	//对查询的类别进行分页
	@Override
	public PageBean<Category> categoryByPageBean(PageBean pb) throws SQLException {
		
		List<Category> result = cd.categoryByPageBean(pb);
		
		int count = cd.selectCategory();
		
		pb.setResult(result);
		pb.setTotalCount(count);
		
		return pb;	
	}

	
	//查询所有类别
	@Override
	public List<Category> findCategoryList() throws SQLException {
		
		return cd.findCategoryList();
	}
}

(8)CategoryDao.java


package com.zql.dao;

import java.sql.SQLException;
import java.util.List;

import com.zql.pojo.Category;
import com.zql.utils.PageBean;

/**

* author:Daniel

* version:1.0

*/

public interface CategoryDao {
	//对查询的类别进行分页
	List<Category> categoryByPageBean(PageBean pb) throws SQLException;
	int selectCategory() throws SQLException;
	//查询所有类别
	List<Category> findCategoryList() throws SQLException;
}

(9) CategoryDaoImpl.java


package com.zql.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.zql.dao.CategoryDao;
import com.zql.pojo.Category;
import com.zql.utils.C3P0Utils;
import com.zql.utils.PageBean;

/**

* author:Daniel

* version:1.0

*/

public class CategoryDaoImpl implements CategoryDao{
	
	private QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
	//对查询的类别进行分页
	@Override
	public List<Category> categoryByPageBean(PageBean pb) throws SQLException {
		String sql = "select * from category limit ?,?";
		Object[] params = {pb.getStartIndex(),pb.getPageSize()};
		
		return qr.query(sql, new BeanListHandler<Category>(Category.class),params);
	}

	//查询总记录数
	@Override
	public int selectCategory() throws SQLException {
		String sql = "select count(*) from category";
		Long count = (Long) qr.query(sql,new ScalarHandler());
		return count.intValue();
	}
	//查询所有类别
	@Override
	public List<Category> findCategoryList() throws SQLException {
		String sql = "select * from category";
		return qr.query(sql, new BeanListHandler<Category>(Category.class));
	}
}

(10) admin/category_list.jsp<三步走>

(10.1)查询部分

<tbody>
        
        	<c:if test="${not empty pb.result }"></c:if>
        		<c:forEach items="${pb.result }" var="v" varStatus="vs">
        			<tr>
					        <td><input name="" type="checkbox" value="" /></td>
					        <td>${vs.count }</td>
					        <td>${v.cname }</td>
					        <td>
					        	<c:if test="${v.state == 1 }">启用</c:if>
					        	<c:if test="${v.state == 0 }">未启用</c:if>
					        </td>
					        <td>${v.order_number}</td>
					        <td>${v.create_time }</td>
					        <td>.....</td>
					        <td>
					        	<a href="">修改</a>
					        	&nbsp;
					        	<a href="javascript:void(0)" onclick="del()" >删除</a>
					        </td>
	       			 </tr>
        		
        		</c:forEach>	
        </tbody>

(10.1)分页部分
在这里插入图片描述
(10.3)完整代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>商品分类</title>
<link href="${pageContext.request.contextPath}/admin/css/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script>

<script type="text/javascript">

// old write 
$(document).ready(function(){
  $(".click").click(function(){
  $(".tip").fadeIn(200);
  });
  
  $(".tiptop a").click(function(){
  $(".tip").fadeOut(200);
});

  $(".sure").click(function(){
  $(".tip").fadeOut(100);
});

  $(".cancel").click(function(){
  $(".tip").fadeOut(100);
});
});
</script>
</head>
<body>

	<div class="place">
    <span>位置:</span>
    <ul class="placeul">
    <li><a href="#">分类管理</a></li>
    </ul>
    </div>
    
    <div class="rightinfo">
    
    <div class="tools">
    
    	<ul class="toolbar">
        <%-- <li class="click"><span><img src="${pageContext.request.contextPath}/admin/images/t02.png" /></span>修改</li>
        <li><span><img src="${pageContext.request.contextPath}/admin/images/t04.png" /></span>统计</li> --%>
        <li style="cursor: pointer;" id="add_category"><span><img src="${pageContext.request.contextPath}/admin/images/t01.png"  /></span>添加类别</li>
        <li style="cursor: pointer;" id=""><span><img src="${pageContext.request.contextPath}/admin/images/t03.png" /></span>批量删除</li>
        </ul>

    </div>
    
    <table class="tablelist">
    	<thead>
    	<tr>
	        <th><input name="" type="checkbox" value="" /></th>
	        <th>序号<i class="sort"><img src="${pageContext.request.contextPath}/admin/images/px.gif" /></i></th>
	        <th>类别名称</th>
	        <th>启用状态</th>
	        <th>排序序号</th>
	        <th>创建时间</th>
	        <th>描述</th>
	        <th>操作</th>
        </tr>
        </thead>
        <tbody>
        
        	<c:if test="${not empty pb.result }"></c:if>
        		<c:forEach items="${pb.result }" var="v" varStatus="vs">
        			<tr>
					        <td><input name="" type="checkbox" value="" /></td>
					        <td>${vs.count }</td>
					        <td>${v.cname }</td>
					        <td>
					        	<c:if test="${v.state == 1 }">启用</c:if>
					        	<c:if test="${v.state == 0 }">未启用</c:if>
					        </td>
					        <td>${v.order_number}</td>
					        <td>${v.create_time }</td>
					        <td>.....</td>
					        <td>
					        	<a href="">修改</a>
					        	&nbsp;
					        	<a href="javascript:void(0)" onclick="del()" >删除</a>
					        </td>
	       			 </tr>
        		</c:forEach>	
        </tbody>
    </table>
<div class="pagin">
    	<div class="message"><i class="blue">${pb.totalCount }</i>条记录,当前显示第&nbsp;<i class="blue">${pb.pageNumber }&nbsp;</i></div>
        <ul class="paginList">
	        
	         <li class="paginItem"><a href="${pageContext.request.contextPath }/category?method=categoryByPageBean&pageNumber=1">首页</a></li>
	         <li class="paginItem"><a href="${pageContext.request.contextPath }/category?method=categoryByPageBean&pageNumber=${pb.pageNumber-1}">上一页</a></li>
	         <li class="paginItem"><a href="${pageContext.request.contextPath }/category?method=categoryByPageBean&pageNumber=${pb.pageNumber+1}">下一页</a></li>
	         <li class="paginItem"><a href="${pageContext.request.contextPath }/category?method=categoryByPageBean&pageNumber=${pb.totalPage}">尾页</a></li>
        </ul>
    </div> 
    <div class="tip">
    	<div class="tiptop"><span>提示信息</span><a></a></div>  
      <div class="tipinfo">
        <span><img src="images/ticon.png" /></span>
        <div class="tipright">
        <p>是否确认对信息的修改 ?</p>
        <cite>如果是请点击确定按钮 ,否则请点取消。</cite>
        </div>
        </div>  
        <div class="tipbtn">
        <input name="" type="button"  class="sure" value="确定" />&nbsp;
        <input name="" type="button"  class="cancel" value="取消" />
        </div>
    </div>
    </div>
    <script type="text/javascript">
	$('.tablelist tbody tr:odd').addClass('odd');
	</script>
</body>
</html>

最终显示:

Java进阶-案例训练(十七)(商城项目(2))_第11张图片

六、分类-添加分类

(1)跳转admin/category_add.jsp添加页面

admin/category_list.jsp

<script type="text/javascript">
	$(function(){
		
		$("#add_category").click(function(){
			location.href="${pageContext.request.contextPath}/admin/category_add.jsp";
		});
	})

</script>

点击“添加类别”如下
Java进阶-案例训练(十七)(商城项目(2))_第12张图片
(2)添加入口路径方法

admin/category_add.jsp
Java进阶-案例训练(十七)(商城项目(2))_第13张图片

${pageContext.request.contextPath }/category?method=addCategory

(3)CategoryServlet.java

//添加分类
	public String addCategory(HttpServletRequest request, HttpServletResponse response)throws Exception {
		//处理数据
		Map<String, String[]> map = request.getParameterMap();
		Category category = new Category();
		
		BeanUtils.populate(category, map);
		
		 cs.addCategory(category);
		
		response.sendRedirect(request.getContextPath()+"/category?method=categoryByPageBean&pageNumber=1");
		return null;
	}

(4)CategoryService.java

//添加类别
	void addCategory(Category category) throws SQLException;

(5)CategoryServiceImpl.java

//添加分类
	@Override
	public void addCategory(Category category) throws SQLException {
		 cd.addCategory(category);	
	}

(6)CategoryDao.java

//添加分类
	void addCategory(Category category) throws SQLException;

(7)CategoryDaoImpl.java

//添加分类
	@Override
	public void addCategory(Category category) throws SQLException {
		
		String sql = "insert into category values(?,?,?,?,?,?)";
		
		Object[] params = {null,category.getCname(),category.getState(),category.getOrder_number(),category.getDescription(),category.getCreate_time()};
		
		qr.update(sql, params);

	}

添加成功显示 :http://localhost:8080/xiaomi/admin/main.jsp

Java进阶-案例训练(十七)(商城项目(2))_第14张图片

七、分类–修改分类

7.1 跳转并回显

(1)在admin/category_list.jsp中添加
在这里插入图片描述

${pageContext.request.contextPath}/category?method=toUpdateCategory&cid=${v.cid}

(2)CategoryServlet.java

//跳转修改页面并回显toUpdateCategory
		public String toUpdateCategory(HttpServletRequest request, HttpServletResponse response)throws Exception {
			//处理数据
			String cid = request.getParameter("cid");
			//业务处理
			Category category = cs.toUpdateCategory(cid);
			//存放到域中
			request.setAttribute("category", category);
			return "/admin/category_update.jsp";
		}

(3)CategoryService.java

//跳转修改页面并回显
	Category toUpdateCategory(String cid) throws SQLException;

(4)CategoryServiceImpl.java

//跳转修改页面并回显
	@Override
	public Category toUpdateCategory(String cid) throws SQLException{
		return cd.toUpdateCategory(cid);
	}
	

(5)CategoryDao.java

//跳转修改页面并回显
	Category toUpdateCategory(String cid) throws SQLException;

(6)CategoryDaoImp.java


	//跳转修改页面并回显
	@Override
	public Category toUpdateCategory(String cid) throws SQLException {
		String sql = "select * from category where cid = ?";
		return qr.query(sql, new BeanHandler<Category>(Category.class),cid);
	}

(7)admin/category_update.jsp

Java进阶-案例训练(十七)(商城项目(2))_第15张图片
完整代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>添加类别</title>
<link href="${pageContext.request.contextPath}/admin/css/style.css" rel="stylesheet" type="text/css" />

<script language="javascript" type="text/javascript" src="${pageContext.request.contextPath}/admin/js/My97DatePicker/WdatePicker.js"></script>
</head>

<body>

	<div class="place">
    <span>位置:</span>
    <ul class="placeul">
    <li><a href="#">修改类别</a></li>
    </ul>
    </div>
    
    <div class="formbody">
    
    <div class="formtitle"><span>类别信息</span></div>
    
    <form action="" method="post">
    	
    	<!-- 获取ID值 -->
    	<input name="cid" type="hidden" value="${category.cid }" />
    	
	    <ul class="forminfo">
		    <li><label>类别名称</label><input name="cname" type="text" value="${category.cname }" class="dfinput" /><i>类别名称不能超过30个字符</i></li>
		    <li><label>是否启用</label>
			    <cite>
				    <input name="status" type="radio" value="1" <c:if test="${category.state == 1 }">checked</c:if>/>&nbsp;&nbsp;&nbsp;&nbsp;
				    	
				    <input name="status" type="radio" value="0" <c:if test="${category.state == 0 }">checked</c:if>/></cite>
		    </li>
		    
		    <li><label>排序序号</label>
		    	<input name="order_number" type="text" value="${category.order_number }" class="dfinput" /><i>输入数字,越大越靠后排列</i>
		    </li>
		    
		    <li><label>类别描述</label>
		    	<textarea name="description" cols="" rows="" class="textinput"  >${category.description }</textarea>
		    </li>
		    
		    <li><label>创建时间</label>
		    	
		    	<input class="Wdate" style="width: 345px;height: 32px;line-height: 32px;"  onClick="WdatePicker({el:this,dateFmt:'yyyy-MM-dd HH:mm:ss'})" 
		    	name="create_time" type="text" class="dfinput" value="${category.create_time }" />
		    </li>
		    
		    <li><label>&nbsp;</label><input type="submit" class="btn" value="确认修改"/></li>
	    </ul>
    </form>
    </div>
</body>
</html>

点击修改前:
Java进阶-案例训练(十七)(商城项目(2))_第16张图片

点击修改后(回显):

Java进阶-案例训练(十七)(商城项目(2))_第17张图片

7.2 修改并保存

(1)在admin/category_update.jsp添加
Java进阶-案例训练(十七)(商城项目(2))_第18张图片

${pageContext.request.contextPath}/category?method=toUpdate

(2)CategoryServlet.java

//修改后的保存toUpdate
	public String toUpdate(HttpServletRequest request, HttpServletResponse response)throws Exception {
		//处理数据
		Map<String, String[]> map = request.getParameterMap();
		Category category = new Category();
		
		BeanUtils.populate(category, map);
		
		 cs.toUpdate(category);
		
		response.sendRedirect(request.getContextPath()+"/category?method=categoryByPageBean&pageNumber=1");
		return null;
	}

(3)CategoryService.java

//修改后的保存toUpdate
	void toUpdate(Category category) throws SQLException;

(4)CategoryServiceImpl.java

//修改后的保存toUpdate
	@Override
	public void toUpdate(Category category) throws SQLException {
		cd.toUpdate(category);
		
	}

(5)CategoryDao.java

//修改后的保存
	void toUpdate(Category category)  throws SQLException;

(6)CategoryDaoImp.java

//去修改后的保存
	@Override
	public void toUpdate(Category category) throws SQLException {
		
		String sql = "update category set cname=?,state=?,order_number=?,description=?,create_time=? where cid=?";
		
		Object[] param = {category.getCname(),category.getState(),category.getOrder_number(),
				category.getDescription(),category.getCreate_time(),category.getCid()};
		
		qr.update(sql,param);
		
	}

(7)最终显示

修改前:

Java进阶-案例训练(十七)(商城项目(2))_第19张图片
修改后:

Java进阶-案例训练(十七)(商城项目(2))_第20张图片

八、分类–分类删除

需求:删除上面修改的一条记录

(1) 在admin/category_list.jsp中添加如下,根据cid删除

在这里插入图片描述
(2)友好提示对接后端

admin/category_list.jsp

Java进阶-案例训练(十七)(商城项目(2))_第21张图片

/* 通过cid删除Category */
function del(cid){
		if(confirm("兄台,您确定删除么?")){
			location.href="${pageContext.request.contextPath}/category?method=delCategoryByCid&cid="+cid;
		}
	}

(3)CategoryServlet.java

//通过cid删除Category
	public String delCategoryByCid(HttpServletRequest request, HttpServletResponse response)throws Exception {
		//处理数据
		String cid = request.getParameter("cid");
		
		cs.delCategoryByCid(cid);
		
		response.sendRedirect(request.getContextPath()+"/category?method=categoryByPageBean&pageNumber=1");
		return null;
	}

(4)CategoryService.java

//通过cid删除Category
	void delCategoryByCid(String cid) throws SQLException;

(5)CategoryServiceImpl.java

//通过cid删除Category
	@Override
	public void delCategoryByCid(String cid) throws SQLException {
		cd.delCategoryByCid(cid);
	}

(6)CategoryDao.java

//通过cid删除Category
	void delCategoryByCid(String cid) throws SQLException;

(7)CategoryDaoImpl.java

//通过cid删除Category
	@Override
	public void delCategoryByCid(String cid) throws SQLException {
		String sql = "delete from category where cid=?";
		qr.update(sql,cid);
	}

最终显示
删除前:显示17条记录
删除后:
Java进阶-案例训练(十七)(商城项目(2))_第22张图片

你可能感兴趣的:(#,计算机(Java进阶)初级进阶,阶段,java,servlet,开发语言,json)