Day74 综合案例

1.思维导图

Day74 综合案例2.代码部分

登录功能

  • 基本功能
//UserServlet.java
@WebServlet(name = "UserServlet" ,urlPatterns = "/user") public class UserServlet extends BaseServlet { private UserService userService = new UserServiceImpl(); public String login(HttpServletRequest request , HttpServletResponse response){ User user = new User(); try { BeanUtils.populate(user,request.getParameterMap()); User existUser = userService.login(user); if (null == existUser) { //登录失败 request.setAttribute("errorMsg","账户或密码错误"); return "login.jsp"; } else { //登录成功 request.getSession().setAttribute("existUser",existUser); return "redirect:index.jsp"; } } catch (Exception e) { e.printStackTrace(); } request.setAttribute("errorMsg","登录失败"); return "login.jsp"; } }
//BaseServlet.java
public class BaseServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String methodName = request.getParameter("methodName"); try { Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class); if (null != method) { String returnValue = (String) method.invoke(this,request,response); if (null != returnValue) { //是否有":" int index = returnValue.lastIndexOf(":"); if (-1 == index) { //没有":" request.getRequestDispatcher(returnValue).forward(request,response); } else { //有":" String path = returnValue.substring(index + 1); if (returnValue.startsWith("redirect")){ //重定向 response.sendRedirect(request.getContextPath() + File.separator + path); } else if (returnValue.startsWith("forward")){ //请求转发 request.getRequestDispatcher(path).forward(request,response); } } } } } catch (Exception e) { e.printStackTrace(); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
  •  随机验证码 / 表单校验
<head>
    <title>用户登录</title>
    <script src="${pageContext.request.contextPath}/js/jquery-3.2.1.min.js"></script>
    <script>

        /**
         * 刷新随机验证码
         */
        function refreshCode() {
            console.log("refreshCode");
            //${pageContext.request.contextPath}/validatecode.jsp 相当于 一张图片
            $("#validateCode").attr("src","${pageContext.request.contextPath}/validatecode.jsp?"+Math.random());
        }
        /**
         * 表单校验 : 后台校验、前端校验
         * 假设,使用后台校验,先发起请求,再做判断,如果校验不通过
         * 使用前端校验,不需要发起请求
         */
        function checkInfo() {
            return checkNull("username") && checkLength("username") && checkRule("username") &&
                   checkNull("password") && checkLength("password") && checkRule("password") ;
        }

        function checkNull(id) {
            var value = $("#"+id).val();
            var reg = /^\s*$/
            if (reg.test(value)) {
                //为空
                $("#error").html(id+"不能为空");
                return false;
            } else {
                //不为空
                return true;
            }
        }
function checkLength(id) { var value = $("#"+id).val(); if (value.length >= 6 && value.length <= 9) { return true; } else { $("#error").html(id+"长度在6~9之间"); return false; } } /** * 校验账户和密码 */ function checkRule(id) { var value = $("#"+id).val(); var reg = /^[a-z0-9]{6,9}$/ if (reg.test(value)) { return true; } else { $("#error").html(id+"由小写字母、数字组成"); return false; } } </script> </head> <body> <font color="red" id="error">${errorMsg}</font> <form action="${pageContext.request.contextPath}/user" method="post" onsubmit="return checkInfo()"> <input type="hidden" name="methodName" value="login"/> 账户:<input type="text" name="username" id="username"/><br> 密码:<input type="text" name="password" id="password"/><br> 验证码:<input type="text" name="validateCode"/> <img id="validateCode" onclick="refreshCode()" src="${pageContext.request.contextPath}/validatecode.jsp"><br> <button type="submit">登录</button> </form> </body>

注册功能

  • 用户列表后台代
//UserServlet.java
public void selectUserListByPage(HttpServletRequest request , HttpServletResponse response){ String currentPageStr = request.getParameter("currentPage"); //获取当前页数 Integer currentPage = getCurrentPage(currentPageStr); try { PageBean<User> pageBean = userService.selectUserListByPage(currentPage); //将PageBean转换成json字符串,并将json字符串响应到浏览器 JsonUtils.writeJsonStr(response,pageBean); } catch (Exception e) { e.printStackTrace(); } }
   //UserService.java
  @Override public PageBean<User> selectUserListByPage(Integer currentPage) throws Exception { PageBean<User> pageBean = new PageBean<>(); //设置当前页数 pageBean.setCurrentPage(currentPage); //设置总记录数 Integer totalSize = userDao.selectTotalSize(); pageBean.setTotalSize(totalSize); //设置每页记录数 Integer pageSize = 3; pageBean.setPageSize(pageSize); //设置总页数 Integer totalPage = ( totalSize % pageSize == 0 ) ? ( totalSize / pageSize ) : ( totalSize / pageSize + 1 ); pageBean.setTotalPage(totalPage); //设置当前页数据: select * from tb_user limit ? , ?; Integer begin = (currentPage - 1) * pageSize; List<User> userList = userDao.selectUserListByPage(begin, pageSize); pageBean.setList(userList); return pageBean; }
  • 用户列表之页面
<head>
    <title>首页</title>
    <script src="${pageContext.request.contextPath}/js/jquery-3.2.1.min.js"></script>
    <script>
      /**
       * 分页查询用户列表
       * @param currentPage 当前页数
       */
      function selectUserListByPage(currentPage){

        console.log("selectUserListByPage selectUserListByPage selectUserListByPage")
        //异步加载列表数据
        $.get("${pageContext.request.contextPath}/user",{
          "methodName":"selectUserListByPage",
          "currentPage":currentPage
        },function (data) {
          //data就是PageBean(js对象)
          var pageBean = data;
          //就是table的标签内容
          var html = "";
          html += "<tr>";
          html += "<td>ID</td>";
          html += "<td>账户</td>";
          html += "<td>密码</td>";
          html += "</tr>";
          var list = pageBean.list;
          $(list).each(function (index) {
            html += "<tr>";
            html += "<td>" + this.id + "</td>";
            html += "<td>" + this.username + "</td>";
            html += "<td>" + this.password + "</td>";
            html += "</tr>";
          })
          // 第1/10页 总记录数:100 每页显示10条 [首页] [上一页] [下一页] [尾页]
          html += "<tr>";
          html += "<td colspan='3'>";
          html += "第" + pageBean.currentPage + "/" + pageBean.totalPage + "页 总记录数:" + pageBean.totalSize + " 每页显示" + pageBean.pageSize + "条";

          if (1 != pageBean.currentPage) {
            //显示首页、上一页
            html += "&nbsp;&nbsp;&nbsp;<a href='javascript:void(0);' onclick='selectUserListByPage(1)'>首页</a>";
            html += "&nbsp;&nbsp;&nbsp;<a href='javascript:void(0);' onclick='selectUserListByPage(" + (pageBean.currentPage - 1) + ")'>上一页</a>";
          }

          if (pageBean.totalPage != pageBean.currentPage) {
            //显示尾页、下一页
            html += "&nbsp;&nbsp;&nbsp;<a href='javascript:void(0);' onclick='selectUserListByPage(" + (pageBean.currentPage + 1) + ")'>下一页</a>";
            html += "&nbsp;&nbsp;&nbsp;<a href='javascript:void(0);' onclick='selectUserListByPage(" + pageBean.totalPage + ")'>尾页</a>";
          }
          html + "</td>"
          html += "</tr>";
          $("#tbl").html(html);
        },"json");
      }

      $(function () {
        selectUserListByPage(2);
      })
    </script>
  </head>
  <body>
    <table id="tbl" border="1px" cellspacing="0px" cellpadding="15px" width="600px" height="200px"> </table>
  </body>
  • 删除用户
/**
* 删除用户
*/
function deleteUser(id){

    var flag = confirm("确认删除该用户?")
    if (flag) {
        //发起删除用户异步请求
        $.post("${pageContext.request.contextPath}/user",{
            "methodName":"deleteUser",
            "id":id
        },function (data) {
            console.log(data);


            if (data.flag) {
                //如果删除成功,刷新用户列表,就是分页查询用户列表
                selectUserListByPage(1);
            }
            //如果删除失败,不做处理
        },"json");
    }
}
//UserServlet.java
public void deleteUser(HttpServletRequest request , HttpServletResponse response){ Integer id = Integer.parseInt(request.getParameter("id")); boolean flag = true; String msg = "删除成功"; try { userService.deleteUserById(id); flag = true; msg = "删除成功"; } catch (Exception e) { e.printStackTrace(); flag = false; msg = "删除失败"; } Map<String,Object> map = new HashMap<>(); map.put("flag",flag); map.put("msg",msg); JsonUtils.writeJsonStr(response,map); }
  • 批量删除
function deleteUsers(){
    var eles = $(".ids:checked");
    if (0 == eles.length) {
        alert("请选择要删除的选项!!")
    } else {

        var flag = confirm("确认删除这些用户吗?")
        if (flag) {
            var ids = [];
            eles.each(function (index) {
                var id = $(this).val();
                ids.push(id);
            })
            var idsStr = ids.join(",");

            $.post("${pageContext.request.contextPath}/user",{
                "methodName":"deleteUsers",
                "ids": idsStr
            },function (data) {
                if (data.flag) {
                    selectUserListByPage(1);
                }
            },"json");
        }
    }
}
//UserServlet.java
public void deleteUsers(HttpServletRequest request , HttpServletResponse response){ String idsStr = request.getParameter("ids"); System.out.println(idsStr); String[] ids = idsStr.split(","); boolean flag = true; String msg = "删除成功"; for (String id : ids) { try { userService.deleteUserById(Integer.parseInt(id)); flag = true; msg = "删除成功"; } catch (Exception e) { e.printStackTrace(); flag = false; msg = "删除失败"; break; } } Map<String,Object> map = new HashMap<>(); map.put("flag",flag); map.put("msg",msg); JsonUtils.writeJsonStr(response,map); }

 

上一篇:分页查询


下一篇:C. Almost Arithmetical Progression(DP)