【javaWeb】javaWeb综合案例

用户综合案例

  • 01_用户列表
  • 02_删除用户
  • 03_批量删除
  • 04_添加用户
  • 05_修改用户
  • 06_BaseServlet的应用
  • 07_BaseServlet的优化

01_用户列表

  • 开发步骤
    • 获取用户列表放到首页完成
      • 登录状态才需要获取用户列表
  • 代码实现
    • UserDao
 @Override
          public List<User> selectUserList() throws Exception {
              return new QueryRunner(JDBCUtil.getDataSource())
                      .query("select * from tb_user",
                              new BeanListHandler<User>(User.class));
          }
  • ShowIndexSerlvet
      @WebServlet(name = "ShowIndexServlet" ,urlPatterns = "/showIndex")
      public class ShowIndexServlet extends HttpServlet {
          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              User existUser = (User) request.getSession().getAttribute("existUser");
              StringBuffer responseBody = new StringBuffer();
              if (null != existUser) {
                  //已经在登录状态
                  responseBody.append("欢迎回来~ " + existUser.getUsername());
                  responseBody.append(" 注销
"
); //获取用户列表 UserDao userDao = new UserDaoImpl(); try { List<User> userList = userDao.selectUserList(); System.out.println(userList); responseBody.append(""); responseBody.append(""); responseBody.append(""); responseBody.append(""); responseBody.append(""); responseBody.append("");for(User user : userList){//遍历一个User对象,对应就应该有一个tr responseBody.append(""); responseBody.append(""); responseBody.append(""); responseBody.append(""); responseBody.append("");} responseBody.append("
ID账户密码
"+user.getId()+""+user.getUsername()+""+user.getPassword()+"
"
); } catch (Exception e) { e.printStackTrace(); } } else { //不在登录状态 responseBody.append("您还没有登录,请登录
"
); } response.setContentType("text/html;charset=utf-8"); response.getWriter().write(responseBody.toString()); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } }

02_删除用户

  • 开发步骤
    • 首页,给每一个记录后面添加一个删除按钮
    • 用户列表不要显示当前登录用户
  • 代码实现
    • UserDao
 @Override
          public void deleteUserById(Integer id) throws Exception {
              new QueryRunner(JDBCUtil.getDataSource())
                      .update("delete from tb_user where id = ?",
                              id);
          }
  • ShowIndexServlet
 responseBody.append("");
      responseBody.append("");
      responseBody.append("");
      responseBody.append("");
      responseBody.append("");
      responseBody.append("");
      responseBody.append("");for(User user : userList){if( user.getId()!= existUser.getId()){//遍历一个User对象,对应就应该有一个tr
              responseBody.append("");
              responseBody.append("");
              responseBody.append("");
              responseBody.append("");
              responseBody.append("");
              responseBody.append("");}}
      
      responseBody.append("
ID账户密码操作
"+user.getId()+""+user.getUsername()+""+user.getPassword()+"删除
"
);
  • DeleteUserServlet
 @WebServlet(name = "DeleteUserServlet" ,urlPatterns = "/deleteUser")
      public class DeleteUserServlet extends HttpServlet {
          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              String idStr = request.getParameter("id");
              Integer id = Integer.parseInt(idStr);
              UserDao userDao = new UserDaoImpl();
              try {
                  userDao.deleteUserById(id);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              response.sendRedirect("/day60/showIndex");
          }
      
          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              doPost(request, response);
          }
      }

03_批量删除

  • 开发流程
    • 在首页需要给每一个记录新加多选框
    • 当点击批量删除按钮之后,完成批量删除操作
  • 代码实现
    • UserDao
 public void deleteUsersByIds(List<Integer> idList) throws Exception {
              for (Integer id : idList) {
                  deleteUserById(id);
              }
          }
  • ShowIndexServlet
 responseBody.append("
"); responseBody.append(""); responseBody.append(""); responseBody.append(""); responseBody.append(""); responseBody.append(""); responseBody.append(""); responseBody.append(""); responseBody.append("");for(User user : userList){if( user.getId()!= existUser.getId()){//遍历一个User对象,对应就应该有一个tr responseBody.append(""); responseBody.append("");...... responseBody.append("");}} responseBody.append("
ID账户密码操作
"
); responseBody.append(""); responseBody.append(""
);

04_添加用户

  • 开发步骤
    • 首页加入一个添加用户按钮
    • 点击添加用户按钮进入到登录页面
  • 代码实现
    • UserDao
  public void addUser(User inputUser) throws Exception {
              new QueryRunner(JDBCUtil.getDataSource())
                      .update("insert into tb_user(username ,password) values(?,?)",
                              inputUser.getUsername(),
                              inputUser.getPassword());
          }
  • ShowIndexServlet
 //已经在登录状态
      responseBody.append("欢迎回来~ " + existUser.getUsername());
      responseBody.append(" 注销
"
); responseBody.append("添加用户
"
); - AddUserServlet @WebServlet(name = "AddUserServlet" ,urlPatterns = "/addUser") public class AddUserServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); User inputUser = new User(); inputUser.setUsername(username); inputUser.setPassword(password); //方式一:在添加之前,校验下用户名是否存在 //方式二:让username字段有唯一约束! UserDao userDao = new UserDaoImpl(); try { userDao.addUser(inputUser); //添加成功,跳转到首页 response.sendRedirect("/day60/showIndex"); } catch (Exception e) { e.printStackTrace(); //添加失败,跳转到添加用户页面 response.sendRedirect("/day60/add.html"); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }

05_修改用户

  • 开发步骤
    • 首页加入修改按钮
  • 代码实现
    • UserDao
 @Override
          public void updateUser(User user) throws Exception {
              new QueryRunner(JDBCUtil.getDataSource())
                      .update("update tb_user set username = ? , password = ? where id = ?",
                              user.getUsername(),
                              user.getPassword(),
                              user.getId());
          }
  • ShowIndexServlet
  for (User user : userList) {
          if ( user.getId() != existUser.getId()) {
              //遍历一个User对象,对应就应该有一个tr
              responseBody.append("");
              responseBody.append("");
              responseBody.append(""+user.getId()+"");
              responseBody.append(""+user.getUsername()+"");
              responseBody.append(""+user.getPassword()+"");
              responseBody.append("" +
                                  "删除 " +
                                  "修改"+
                                  "");
              responseBody.append("");
          }
      }
  • 显示修改用户页面
 @WebServlet(name = "ShowUpdateUserServlet" , urlPatterns = "/showUpdateUser")
      public class ShowUpdateUserServlet extends HttpServlet {
          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              Integer id = Integer.parseInt(request.getParameter("id"));
              //根据id查询用户
              UserDao userDao = new UserDaoImpl();
              StringBuffer responseBody = new StringBuffer();
              try {
                  User user = userDao.selectUserById(id);
                  System.out.println(user);
                  responseBody.append("
"); responseBody.append(""); responseBody.append("账户:
"
); responseBody.append("密码:
"
); responseBody.append(""); responseBody.append(""
); } catch (Exception e) { e.printStackTrace(); } response.setContentType("text/html;charset=utf-8"); response.getWriter().write(responseBody.toString()); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
  • 修改用户
 @WebServlet(name = "UpdateUserServlet" ,urlPatterns = "/updateUser")
      public class UpdateUserServlet extends HttpServlet {
          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              Integer id = Integer.parseInt(request.getParameter("id"));
              String username = request.getParameter("username");
              String password = request.getParameter("password");
              System.out.println("username : " + username + ", password : " + password);
              //要修改的内容:username、password
              User user = new User(id,username,password);
              UserDao userDao = new UserDaoImpl();
              try {
                  userDao.updateUser(user);
                  //修改成功,跳转到首页
                  response.sendRedirect("/day60/showIndex");
              } catch (Exception e) {
                  e.printStackTrace();
                  //修改失败,跳转到修改页面
                  response.sendRedirect("/day60/showUpdateUser?id="+id);
      
              }
          }
      
      
          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              doPost(request, response);
          }
      }

06_BaseServlet的应用

  • 代码实现
  @WebServlet(name = "UserServlet",urlPatterns = "/user")
      public class UserServlet extends BaseServlet {
      
      
      
          public void login(HttpServletRequest request,HttpServletResponse response){
              String username = request.getParameter("username");
              String password = request.getParameter("password");
              User inputUser = new User();
              inputUser.setUsername(username);
              inputUser.setPassword(password);
              UserDao userDao = new UserDaoImpl();
              try {
                  User existUser = userDao.login(inputUser);
                  if (null == existUser) {
                      //登录失败
                      request.getRequestDispatcher("/login.html").forward(request,response);
                  } else {
                      //登录成功
                      request.getSession().setAttribute("existUser",existUser);
                      response.sendRedirect("/day61/user?methodName=showIndex");
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      
          public void showIndex(HttpServletRequest request , HttpServletResponse response) throws Exception {
              System.out.println("showIndex");
              User existUser = (User) request.getSession().getAttribute("existUser");
              StringBuffer responseBody = new StringBuffer();
              if (null != existUser) {
                  //在登录状态
                  responseBody.append("欢迎回来~~~"+existUser.getUsername());
                  responseBody.append("注销登录");
              } else {
                  //不在登录状态
                  responseBody.append("您还没有登录;");
                  responseBody.append("请登录");
              }
              response.setContentType("text/html;charset=utf-8");
              response.getWriter().write(responseBody.toString());
          }
      
          public void logout(HttpServletRequest request , HttpServletResponse response) throws Exception {
              request.getSession().invalidate();
              response.sendRedirect("/day61/login.html");
          }
      
      
      }

07_BaseServlet的优化

  • BaseServlet优化
    • 资源跳转问题
    • 响应正文中文乱码
  • 代码实现
 @WebServlet(name = "BaseServlet",urlPatterns = "/base")
      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()+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);
          }
      }

你可能感兴趣的:(JavaWeb)