回顾:

  1. form表单、ServletdbutilsFilterEL表达式、JSTL标签

一、管理员登录

admin/login.jsp

  1. <form action="/dami/user" method="post">
  2. <input type="hidden" name="method" value="adminLogin">
  3. <ul>
  4. <li><span color="red">${msg}</span></li>
  5. <li><input name="username" type="text" class="loginuser" value="" onclick="JavaScript:this.value=''"/></li>
  6. <li><input name="password" type="password" class="loginpwd" value="" onclick="JavaScript:this.value=''"/></li>
  7. <li><input name="" type="submit" class="loginbtn" value="登录" onclick="javascript:window.location='main.html'" /><label><input name="" type="checkbox" value="" checked="checked" />记住密码</label><label><a href="#">忘记密码?</a></label></li>
  8. </ul>
  9. </form>

image.png
先看WEB-INF目录下访问UserServlet是什么地址栏路径

Servlet:

  1. //管理员登录
  2. protected void adminLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  3. //1、获取数据
  4. String username = request.getParameter("username");
  5. String password = request.getParameter("password");
  6. //2、调用业务
  7. UserService us = new UserService();
  8. User user = us.adminLogin(username,password);
  9. //3、结果展示
  10. if(user != null) {
  11. //登录成功
  12. response.sendRedirect("/dami/admin/main.jsp");
  13. }else {
  14. //登录失败 跳转到login.jsp
  15. request.setAttribute("msg", "用户名密码错误或者不是管理员身份");
  16. request.getRequestDispatcher("/admin/login.jsp").forward(request, response);
  17. }
  18. }

Service:

  1. public User adminLogin(String username, String password) {
  2. return ud.adminLogin(username,password);
  3. }

Dao:

  1. public User adminLogin(String username, String password) {
  2. String sql = "SELECT * FROM USER WHERE username= ? AND PASSWORD = ? AND manager = ?";
  3. Object [] param = {username,password,1};
  4. try {
  5. return qr.query(sql, new BeanHandler<User>(User.class),param);
  6. } catch (SQLException e) {
  7. // TODO Auto-generated catch block
  8. e.printStackTrace();
  9. return null;
  10. }
  11. }

域对象:

  1. request:作用范围:一次请求范围内有效
  2. session:作用范围:一次会话(多次请求)

问题:在index.jsp页面中显示 用户的问题

  1. if(user != null) {
  2. request.getSession().setAttribute("user", user);
  3. //登录成功
  4. response.sendRedirect("/dami/admin/main.jsp");
  5. }

在index.jsp中用EL表达式取:

  1. ${user.username} 早上好,欢迎使用信息管理系统

image.png

二、 管理员退出

思考:

1、点击退出直接跳转到/admin/login.jsp

2、点击退出执行UserServlet,在UserServlet的方法中,移除session中的user信息,然后跳转到登录页面

问题:移除session中用户信息时使用下面哪种方式?

  1. request.getSession().invalidate();//session对象销毁了
  2. request.getSession().removeAttribute("user");//选用

代码实现:

top.jsp

  1. <li><a href="/dami/user?method=adminLogout" target="_parent">退出</a></li>

Servlet:

  1. //管理员退出
  2. protected void adminLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  3. request.getSession().removeAttribute("user");
  4. //跳转到登录页面
  5. response.sendRedirect("/dami/admin/login.jsp");
  6. }

三、用户列表查询

思路:和查询员工列表一样

代码实现:

left.jsp

  1. <li class="active"><cite></cite><a href="/dami/user?method=selectUlist" target="rightFrame">用户管理</a><i></i></li>

Servlet:

  1. //查询所有用户
  2. protected void selectUlist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  3. //1、获取数据(暂无)
  4. //2、调用业务
  5. UserService us = new UserService();
  6. List<User> ulist = us.selectUlist();
  7. //3、结果的展示
  8. request.setAttribute("ulist", ulist);
  9. request.getRequestDispatcher("/admin/user_list.jsp").forward(request, response);
  10. }

Service:

  1. public List<User> selectUlist() {
  2. // TODO Auto-generated method stub
  3. return ud.selectUlist();
  4. }

Dao:

  1. public List<User> selectUlist() {
  2. String sql = "select * from user";
  3. try {
  4. return qr.query(sql, new BeanListHandler<User>(User.class));
  5. } catch (SQLException e) {
  6. // TODO Auto-generated catch block
  7. e.printStackTrace();
  8. return null;
  9. }
  10. }

user_list.jsp数据的显示:

  1. <c:if test="${not empty ulist}">
  2. <c:forEach items="${ulist}" var="u" varStatus="vs">
  3. <tr>
  4. <td><input name="ids" type="checkbox" value=""/></td>
  5. <td>${vs.count}</td>
  6. <td>${u.name}</td>
  7. <td>
  8. <c:if test="${u.sex ==1}">男</c:if>
  9. <c:if test="${u.sex ==0}">女</c:if>
  10. </td>
  11. <td>${u.phone_number}</td>
  12. <td>${u.area}</td>
  13. <td>
  14. <c:if test="${u.manager ==1}">管理员</c:if>
  15. <c:if test="${u.manager ==0}">普通用户</c:if>
  16. </td>
  17. <td>${u.username}</td>
  18. <td style="text-align: center;">
  19. <img src="/xm_upload/${u.photo}" width="80" height="50" alt="" />
  20. </td>
  21. <td>
  22. </td>
  23. </tr>
  24. </c:forEach>
  25. </c:if>

image.png

四、用户分页的显示

分析图:

image.png

Mysql的分页的Sql:

  1. /*
  2. 需求:每页显示两条数据
  3. limit:分页的关键字 之后跟两个参数
  4. 参数1:起始索引 从0开始 计算的
  5. 参数2:每页显示的条数
  6. */
  7. #第一页
  8. SELECT * FROM USER LIMIT 0,2;
  9. #第二页
  10. SELECT * FROM USER LIMIT 2,2;
  11. #第三页
  12. SELECT * FROM USER LIMIT 4,2;

核心点:limit 后两个参数

两个公式:

  • 计算起始索引
    起始索引 = (当前页 - 1) * 每页显示的条数
    每页显示的条数:一般给一个固定的值
    当前页:从页面传过来
  • 计算总页数
    总页数 = 总记录数 % 每页显示的条数 == 0 ? (总记录数 / 每页显示的条数) : (总记录数 / 每页显示的条数 +1)
    总记录:select count(*) from user
    每页显示的条数:设置好了

代码实现:

left.jsp:

  1. <li class="active"><cite></cite><a href="/dami/user?method=selectUlist&pageNumber=1" target="rightFrame">用户管理</a><i></i></li>

Servlet:

  1. //查询所有用户
  2. protected void selectUlist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  3. //1、获取数据(暂无)
  4. //获取当前页
  5. String pageNumber = request.getParameter("pageNumber");
  6. PageBean<User> pb = new PageBean<User>();
  7. pb.setPageNumber(Integer.parseInt(pageNumber));
  8. pb.setPageSize(2);
  9. //2、调用业务
  10. UserService us = new UserService();
  11. pb = us.selectUlist(pb);
  12. //3、结果的展示
  13. request.setAttribute("pb", pb);
  14. request.getRequestDispatcher("/admin/user_list.jsp").forward(request, response);
  15. }

Service:

  1. public PageBean<User> selectUlist(PageBean<User> pb) {
  2. List<User> ulist = ud.selectUlist(pb);
  3. pb.setResult(ulist);
  4. //查询总记录数
  5. int totalCount = ud.selecCount();
  6. pb.setTotalCount(totalCount);
  7. return pb;
  8. }

Dao:

  1. public List<User> selectUlist(PageBean<User> pb) {
  2. String sql = "select * from user limit ?,?";
  3. try {
  4. Object [] param = {pb.getStartIndex(),pb.getPageSize()};
  5. return qr.query(sql, new BeanListHandler<User>(User.class),param);
  6. } catch (SQLException e) {
  7. // TODO Auto-generated catch block
  8. e.printStackTrace();
  9. return null;
  10. }
  11. }
  12. //查询总记录数
  13. public int selecCount() {
  14. String sql = "select count(*) from user";
  15. try {
  16. Long count = (Long) qr.query(sql, new ScalarHandler());
  17. return count.intValue();
  18. } catch (SQLException e) {
  19. // TODO Auto-generated catch block
  20. e.printStackTrace();
  21. return 0;
  22. }
  23. }

user_list.jsp

  1. <c:if test="${not empty pb.result}">
  2. <c:forEach items="${pb.result}" var="u" varStatus="vs">
  3. <div class="pagin">
  4. <div class="message">共<i class="blue">${pb.totalCount}</i>条记录,当前显示第&nbsp;<i class="blue">${pb.pageNumber}&nbsp;</i>页</div>
  5. <ul class="paginList">
  6. <li class="paginItem"><a href="/dami/user?method=selectUlist&pageNumber=1">首页</a></li>
  7. <c:if test="${pb.pageNumber != 1}">
  8. <li class="paginItem"><a href="/dami/user?method=selectUlist&pageNumber=${pb.pageNumber-1}">上一页</a></li>
  9. </c:if>
  10. <!--索引页 -->
  11. <c:forEach begin="1" end="${pb.totalPage}" var="i">
  12. <li class="paginItem"><a href="/dami/user?method=selectUlist&pageNumber=${i}">${i}</a></li>
  13. </c:forEach>
  14. <c:if test="${pb.pageNumber != pb.totalPage}">
  15. <li class="paginItem"><a href="/dami/user?method=selectUlist&pageNumber=${pb.pageNumber+1}">下一页</a></li>
  16. </c:if>
  17. <li class="paginItem"><a href="/dami/user?method=selectUlist&pageNumber=${pb.totalPage}">尾页</a></li>
  18. </ul>
  19. </div>

总结:

  • 分页的sql limit
  • 两个分页的计算公式
  • PageBean的作用 (封装分页相关的数据)
  • 分页条的使用

五、修改用户的权限

分析图:

image.png

代码实现:

user_list.jsp

  1. <td>
  2. <c:if test="${u.manager ==1}">
  3. <a href="/dami/user?method=updateRole&manager=0&uid=${u.uid}"><font color="red">修改为普通用户</font></a>
  4. </c:if>
  5. <c:if test="${u.manager ==0}">
  6. <a href="/dami/user?method=updateRole&manager=1&uid=${u.uid}"><font color="green">修改为管理员</font></a>
  7. </c:if>
  8. </td>

Servelt:

  1. //修改用户的权限
  2. protected void updateRole(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  3. //1、获取数据
  4. String manager = request.getParameter("manager");
  5. String uid = request.getParameter("uid");
  6. //2、调用业务
  7. UserService us = new UserService();
  8. int row = us.updateRole(manager,uid);
  9. //3、结果的展示
  10. response.sendRedirect("/dami/user?method=selectUlist&pageNumber=1");
  11. }

Service:

  1. public int updateRole(String manager, String uid) {
  2. return ud.updateRole(manager,uid);
  3. }

Dao:

  1. public int updateRole(String manager, String uid) {
  2. String sql ="update user set manager = ? where uid = ?";
  3. Object [] param = {manager,uid};
  4. try {
  5. return qr.update(sql, param);
  6. } catch (SQLException e) {
  7. // TODO Auto-generated catch block
  8. e.printStackTrace();
  9. return 0;
  10. }
  11. }

image.png

六、批量删除

6.1 全选效果的实现

思路分析图:

image.png

代码实现:

user_list.jsp

  1. <th><input id="checkbox_main" type="checkbox" onclick="quan()"/></th>
  2. <td><input name="ids" class="ids" type="checkbox" value=""/></td>
  3. <script type="text/javascript">
  4. //全选效果
  5. function quan(){
  6. //1、获取全选框的选中状态 true:选中 false:未选中
  7. var flag = $("#checkbox_main").prop("checked");
  8. //2、获取所有复选框元素对象
  9. var idsEle = $(".ids");
  10. //3、将复选框的checked的值设置flag
  11. idsEle.prop("checked",flag);
  12. }
  13. </script>

image.png

6.2 批量删除

思路分析:

image.png

代码实现:

user_list.jsp

  1. <li onclick="batchDelete()" id="batchDelete" style="cursor: pointer;"><span><img src="${pageContext.request.contextPath}/admin/images/t03.png" /></span>批量删除</li>
  2. <script>
  3. //批量删除
  4. function batchDelete(){
  5. if(!confirm("是否确定要批量删除?")){
  6. return;
  7. }
  8. //1、获取所有被选中的复选框对象
  9. var idsEle = $(".ids:checked");
  10. var ids = "";
  11. //2、遍历元素对象
  12. idsEle.each(function(){
  13. //获取复选框的value值
  14. var id = this.value;
  15. //拼接id值
  16. ids += ","+id;
  17. })
  18. //截取ids ,6,5,4
  19. ids = ids.substring(1); // 6,5,4
  20. //向服务器发送ids值
  21. location.href = "/dami/user?method=batchDelete&ids="+ids;
  22. }
  23. </script>

//location:服务器地址栏的地址

Servlet:

  1. //批量删除
  2. protected void batchDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  3. //1、获取数据
  4. String ids = request.getParameter("ids");
  5. //2、调用业务
  6. UserService us = new UserService();
  7. int row = us.batchDelete(ids);
  8. //3、结果的展示
  9. if(row >0) {
  10. response.sendRedirect("/dami/user?method=selectUlist&pageNumber=1");
  11. }else {
  12. response.getWriter().write("删除失败!!!!");
  13. }
  14. }

Service:

  1. public int batchDelete(String ids) {
  2. // TODO Auto-generated method stub
  3. return ud.batchDelete(ids);
  4. }

Dao:

  1. public int batchDelete(String ids) {
  2. String sql = "delete from user where uid in ("+ids+")";
  3. try {
  4. return qr.update(sql);
  5. } catch (SQLException e) {
  6. // TODO Auto-generated catch block
  7. e.printStackTrace();
  8. return 0;
  9. }
  10. }

image.png
image.png!!

七、分类管理的分页查询

思路:和用户的分页查询一样

商品分类表category:

  1. CREATE TABLE `category` (
  2. `cid` INT(10) PRIMARY KEY AUTO_INCREMENT,#主键自增
  3. `cname` VARCHAR(50) NOT NULL,#分类名称
  4. `state` INT(1) DEFAULT NULL,#状态 是否启用 1:启用 0:不启用
  5. `order_number` INT(5) DEFAULT NULL,#排序号
  6. `description` VARCHAR(100) DEFAULT NULL,#分类描述
  7. `create_time` DATETIME # 创建时间
  8. );

状态 是否启用 1:启用 0:不启用
为什么不删掉:方便以后看

和表对应的Category类、dao、service、servlet

代码略

八、添加分类

category_list.jsp

  1. <li onclick="toAdd()" style="cursor: pointer;" id="add_category"><span><img src="${pageContext.request.contextPath}/admin/images/t01.png" /></span>添加类别</li>
  2. <script type="text/javascript">
  3. //跳转到category_add.jsp
  4. function toAdd(){
  5. location.href = "/dami/admin/category_add.jsp";
  6. }
  7. </script>

category_add.jsp

注意:将页面给的status修改state

  1. <form action="/dami/category" method="post">
  2. <input type="hidden" name="method" value="addCategory">
  3. <input name="state" type="radio"

Servlet:

  1. //添加分类
  2. protected void addCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  3. try {
  4. //1、获取数据
  5. //获取表单中的数据
  6. Map<String, String[]> map = request.getParameterMap();
  7. //创建User对象
  8. Category category = new Category();
  9. //BeanUtils工具类(将map中的数据封装到User对象中)
  10. BeanUtils.populate(category, map);
  11. //2、调用业务
  12. CategoryService cs = new CategoryService();
  13. cs.addCategory(category);
  14. //3、结果的展示
  15. response.sendRedirect("/dami/category?method=selectClist&pageNumber=1");
  16. } catch (IllegalAccessException | InvocationTargetException e) {
  17. // TODO Auto-generated catch block
  18. e.printStackTrace();
  19. }
  20. }

Service:

  1. public void addCategory(Category category) {
  2. cd.addCategory(category);
  3. }

Dao:

  1. public void addCategory(Category c) {
  2. String sql = "insert into category values(?,?,?,?,?,?)";
  3. Object [] param = {null,c.getCname(),c.getState(),c.getOrder_number(),
  4. c.getDescription(),c.getCreate_time()};
  5. try {
  6. qr.update(sql, param);
  7. } catch (SQLException e) {
  8. // TODO Auto-generated catch block
  9. e.printStackTrace();
  10. }
  11. }

九、修改分类信息

9.1 跳转16数据的回显

分析:

  • 要在category_update.jsp 显示该分类的信息
  • 根据cid查询分类信息 select * from categroy where cid = ?
  • 传参数:cid的值

代码实现:

category_list.jsp

  1. <a href="/dami/category?method=toUpdate&cid=${c.cid}">修改</a>

Servlet:

  1. //跳转到category_update.jsp
  2. protected void toUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  3. //1、获取数据
  4. String cid = request.getParameter("cid");
  5. //2、调用业务
  6. CategoryService cs = new CategoryService();
  7. Category category = cs.selectByCid(cid);
  8. //3、结果的展示
  9. request.setAttribute("category", category);
  10. request.getRequestDispatcher("/admin/category_update.jsp").forward(request, response);
  11. }

Service:

  1. public Category selectByCid(String cid) {
  2. // TODO Auto-generated method stub
  3. return cd.selectByCid(cid);
  4. }

Dao:

  1. public Category selectByCid(String cid) {
  2. String sql = "select * from category where cid = ?";
  3. try {
  4. return qr.query(sql, new BeanHandler<Category>(Category.class),cid);
  5. } catch (SQLException e) {
  6. // TODO Auto-generated catch block
  7. e.printStackTrace();
  8. return null;
  9. }
  10. }

category_update.jsp

注意:在value中用el表达式

  1. <li><label>类别名称</label><input name="cname" type="text" value="${category.cname}" class="dfinput" /><i>类别名称不能超过30个字符</i></li>
  2. <li><label>是否启用</label>
  3. <cite>
  4. <input name="status" type="radio" value="1" <c:if test="${category.state == 1}">checked</c:if>/>是&nbsp;&nbsp;&nbsp;&nbsp;
  5. <input name="status" type="radio" value="0" <c:if test="${category.state ==0}">checked</c:if>/>否
  6. </cite>
  7. </li>
  8. 省略....

image.png

问题:什么情况下直接跳转到页面、什么情况下需要请求服务器?

标准:看在跳转的页面中要不要回显数据

9.2 修改分类信息

分析:

  • sql:update category cname =? ,state =?,order_number = ?,description =?,create_time =?
    where cid = ?
  • 和添加分类信息传参数的区别
    添加时:主键是自增的,所以不用传参cid
    修改时:需要传参cid

代码实现:

category_update.jsp

  1. <form action="/dami/category" method="post">
  2. <input type="hidden" name="cid" value="${category.cid}">
  3. <input type="hidden" name="method" value="updateCategory">
  4. <input name="state" type="radio"

Servlet:

  1. //修改分类
  2. protected void updateCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  3. try {
  4. //1、获取数据
  5. //获取表单中的数据
  6. Map<String, String[]> map = request.getParameterMap();
  7. //创建User对象
  8. Category category = new Category();
  9. //BeanUtils工具类(将map中的数据封装到User对象中)
  10. BeanUtils.populate(category, map);
  11. //2、调用业务
  12. CategoryService cs = new CategoryService();
  13. cs.updateCategory(category);
  14. //3、结果的展示
  15. response.sendRedirect("/dami/category?method=selectClist&pageNumber=1");
  16. } catch (IllegalAccessException | InvocationTargetException e) {
  17. // TODO Auto-generated catch block
  18. e.printStackTrace();
  19. }
  20. }

Service:

  1. public void updateCategory(Category category) {
  2. cd.updateCategory(category);
  3. }

Dao:

  1. public void updateCategory(Category c) {
  2. String sql = "update category set cname =?,state =?,order_number = ?,description =?,create_time"
  3. + "=? where cid = ?";
  4. Object [] params = {c.getCname(),c.getState(),c.getOrder_number(),
  5. c.getDescription(),c.getCreate_time(),c.getCid()};
  6. try {
  7. qr.update(sql, params);
  8. } catch (SQLException e) {
  9. // TODO Auto-generated catch block
  10. e.printStackTrace();
  11. }
  12. }