一个dao层有很多功能
public interface UserDao { //获取总记录数 long bookReadCount(); //分页查询用户 List<User> userList(PageBean pageBean); //获取用户列表(分页显示) boolean findUser(String userName); //根据id查看一个用户 User findUser(Integer id); //增加用户 boolean userAdd(User user); //修改用户 boolean userUpdate(User user); //根据id删除一个用户 boolean delUser(int id); //根据一组id字符串批量删除用户 boolean batDelUser(String id); //用户登录 User userLogin(User user); }
初学者一个功能对应一个servlet,一套curd操作下来4,5个servlet很正常
用生成的doGet,doPost只能实现一个功能
@WebServlet("/UserAddServlet") public class UserAddServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String userName = req.getParameter("userName"); String userPwd = req.getParameter("userPwd"); String userSex = req.getParameter("userSex"); String userPhone = req.getParameter("userPhone"); String userEmail = req.getParameter("userEmail"); String userAddress = req.getParameter("userAddress"); User user = new User(); user.setUserName(new String(userName.getBytes("ISO-8859-1"),"utf-8")); user.setUserPwd(userPwd); user.setUserSex(new String(userSex.getBytes("iso-8859-1"),"utf-8")); user.setUserPhone(userPhone); user.setUserEmail(userEmail); user.setUserAddress(new String(userAddress.getBytes("iso-8859-1"),"utf-8")); UserDao dao = new UserDao(); dao.addUser(user); req.getRequestDispatcher("UserShowServlet").forward(req,resp); } }
把一个dao层的功能放到一个servlet里面,有两种思路
第一种配置xml地址,进行条件判断,但是if太多了
@WebServlet(name = "actionServlet",urlPatterns = {"/userByteId","/allUser","/addUser","/updateUser","/deleteUser"})
这个注解等于xml里面的<servlet-mapping>
<!-- <servlet-mapping>-->
<!-- <servlet-name>actionServlet</servlet-name>-->
<!-- <url-pattern>/allUser</url-pattern>-->
<!-- <url-pattern>/dabo/allUser</url-pattern>-->
<!-- <url-pattern>/userByteId</url-pattern>-->
<!-- <url-pattern>/addUser</url-pattern>-->
<!-- <url-pattern>/updateUser</url-pattern>-->
<!-- <url-pattern>/deleteUser</url-pattern>-->
<!-- </servlet-mapping>-->
public class actionServlet extends HttpServlet { UserDao userDao = new UserDao(); User user = new User(); //如何区分发过来的请求,并通过请求调用不通方法处理 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取请求的url地址 String path = req.getRequestURI(); System.out.println(path); //获取最后一个斜杠的下标 int index = path.lastIndexOf("/"); //截取分发的请求 String relaPath = path.substring(index + 1); System.out.println("relaPath=" + relaPath); //根据不同的请求,调用不同的方法处理 if (relaPath.equals("login")) { try { login(req,resp); } catch (Exception e) { e.printStackTrace(); } }else if (relaPath.equals("addUser")){ try { addUser(req,resp); } catch (Exception e) { e.printStackTrace(); } } else if (relaPath.equals("updateUser")) { try { updateUser(req,resp); } catch (Exception e) { e.printStackTrace(); } } else if (relaPath.equals("deleteUser")) { try { deleteUser(req,resp); } catch (Exception e) { e.printStackTrace(); } } else if (relaPath.equals("userByteId")) { try { userByteId(req,resp); } catch (Exception e) { e.printStackTrace(); } }else if (relaPath.equals("allUser")) { try { allUser(req,resp); } catch (Exception e) { e.printStackTrace(); } } }public void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); String userName = req.getParameter("userName"); String userPwd = req.getParameter("userPwd"); String userSex = req.getParameter("userSex"); String userPhone = req.getParameter("userPhone"); String userEmail = req.getParameter("userEmail"); String userAddress = req.getParameter("userAddress"); user.setUserName(userName); user.setUserPwd(userPwd); user.setUserSex(userSex); user.setUserPhone(userPhone); user.setUserEmail(userEmail); user.setUserAddress(userAddress); userDao.addUser(user); req.getRequestDispatcher("allUser").forward(req,resp); } public void updateUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); String userName = req.getParameter("userName"); String userPwd = req.getParameter("userPwd"); String userSex = req.getParameter("userSex"); String userPhone = req.getParameter("userPhone"); String userEmail = req.getParameter("userEmail"); String userAddress = req.getParameter("userAddress"); String id = req.getParameter("id"); user.setUserName(userName); user.setUserPwd(userPwd); user.setUserSex(userSex); user.setUserPhone(userPhone); user.setUserEmail(userEmail); user.setUserAddress(userAddress); user.setId(Integer.valueOf(id)); userDao.updateUser(user); req.getRequestDispatcher("allUser").forward(req,resp); } public void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ String idStr = req.getParameter("id"); if (idStr != null && idStr != "") { int id = Integer.valueOf(idStr); userDao.deleteUser(id); } req.getRequestDispatcher("allUser").forward(req,resp); } public void userByteId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ String idStr = req.getParameter("id"); if (idStr != null && idStr != "") { int id = Integer.valueOf(idStr); user = userDao.selectUserById(id); req.setAttribute("users",user); } req.getRequestDispatcher("updateUser.jsp").forward(req,resp); } public void allUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ List<User> lists = userDao.getAllUser(); req.setAttribute("lists",lists); req.getRequestDispatcher("user.jsp").forward(req,resp); } protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }
第二种,创建一个父类BaseServlet
用反射重写service方法,子类继承截取后缀直接调用对应的方法
1 public class BaseServlet extends HttpServlet { 2 3 @Override 4 protected void service(HttpServletRequest request, HttpServletResponse response) 5 throws ServletException, IOException { 6 // 1、获得方法名称 7 String methodName = request.getParameter("method"); 8 Method method = null; 9 10 // 2、通过方法名和方法所需要的参数获得Method对象 11 try { 12 method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class); 13 } catch (Exception e) { 14 throw new RuntimeException("调用的方法:" + methodName + "不存在", e); 15 } 16 17 // 3、通过Method对象调用方法 18 try { 19 String result = (String) method.invoke(this, request, response); 20 if (result != null && result.trim().length() > 0) {// 如果返回的result不为空 21 int index = result.indexOf(":");// 获得第一个冒号的位置 22 if (index == -1) {// 如果没有冒号,就使用转发 23 request.getRequestDispatcher(result).forward(request, response); 24 } else {// 如果有冒号 25 String start = result.substring(0, index);// 截取前缀 26 String path = result.substring(index + 1);// 截取路径 27 if (start.equalsIgnoreCase("f")) {// 前缀为f表示使用转发 28 request.getRequestDispatcher(path).forward(request, response); 29 } else if (start.equalsIgnoreCase("r")) {// 前缀为r表示使用重定向 30 response.sendRedirect(request.getContextPath() + path); 31 } 32 } 33 } 34 } catch (Exception e) { 35 throw new RuntimeException(e); 36 } 37 } 38 }
1 public class UserManageServlet extends BaseServlet { 2 private static final String USERLIST_PATH = "userManage/userList.jsp";//用户列表页面地址 3 private static final String USERADD_PATH = "userManage/userAdd.jsp";//用户增加页面地址 4 private static final String USEREDIT_PATH = "userManage/userEdit.jsp";//用户修改页面地址 5 private static final String USERDETAIL_PATH = "userManage/userDetail.jsp";//用户修改页面地址 6 7 public void userList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 8 UserDao dao = new UserDaoImpl(); 9 int curPage = 1; 10 String page = req.getParameter("page"); 11 if (page != null) { 12 curPage = Integer.parseInt(page); 13 } 14 //获取xml中设置的每页显示大小参数 15 int maxSize = Integer.parseInt(req.getServletContext().getInitParameter("maxPageSize")); 16 PageBean pageBean = new PageBean(curPage, maxSize, dao.bookReadCount()); 17 req.setAttribute("userList", dao.userList(pageBean)); 18 req.setAttribute("pageBean", pageBean); 19 req.getRequestDispatcher(USERLIST_PATH).forward(req, resp); 20 } 21 22 public void userDel(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 23 int id = Integer.parseInt(req.getParameter("id")); 24 UserDao dao = new UserDaoImpl(); 25 if (dao.delUser(id)) { 26 req.setAttribute("userMessage", "用户已删除"); 27 } else { 28 req.setAttribute("userMessage", "用户删除失败"); 29 } 30 //用户删除成功失败都跳转到用户列表页面 31 userList(req, resp); 32 } 33 34 public String userAddjsp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 35 return USERADD_PATH; 36 } 37 38 public void userAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 39 System.out.println("三大佛充当反锁车方所陈红戳地方戳"); 40 UserDao ad=new UserDaoImpl(); 41 User user=new User( 42 request.getParameter("userName"), 43 request.getParameter("passWord"), 44 request.getParameter("name"), 45 request.getParameter("sex"), 46 Integer.parseInt(request.getParameter("age")), 47 request.getParameter("tell"), 48 request.getParameter("address")); 49 user.setEnabled("y");//默认添加的用户启用 50 //添加之前判断用户名是否在库中存在 51 if(new AdminDaoImpl().findUser(user.getUserName())){ 52 request.setAttribute("userMessage", "用户添加失败!用户名已存在"); 53 request.getRequestDispatcher(USERADD_PATH).forward(request, response); 54 }else{ 55 //执行dao层添加操作 56 if(ad.userAdd(user)){ 57 request.setAttribute("userMessage", "用户添加成功!"); 58 userList(request, response);//通过servlet中listUser跳到用户列表 59 }else{ 60 request.setAttribute("userMessage", "用户添加失败!"); 61 request.getRequestDispatcher(USERADD_PATH).forward(request, response); 62 } 63 } 64 } 65 66 public void datail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 67 String id=request.getParameter("id"); 68 UserDao ud=new UserDaoImpl(); 69 request.setAttribute("userInfo",ud.findUser(Integer.valueOf(id)));//这里回去是User对象 70 request.getRequestDispatcher(USERDETAIL_PATH).forward(request, response); 71 72 } 73 public void userEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 74 String id=request.getParameter("id"); 75 UserDao ud=new UserDaoImpl(); 76 request.setAttribute("userInfo",ud.findUser(Integer.valueOf(id)));//这里回去是User对象 77 request.getRequestDispatcher(USEREDIT_PATH).forward(request, response); 78 79 } 80 81 public void userUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 82 User user=new User( 83 Integer.parseInt(request.getParameter("userId")), 84 request.getParameter("passWord"), 85 request.getParameter("name"), 86 request.getParameter("sex"), 87 Integer.parseInt(request.getParameter("age")), 88 request.getParameter("tell"), 89 request.getParameter("address"), 90 request.getParameter("enabled")); 91 UserDao ud=new UserDaoImpl(); 92 if(ud.userUpdate(user)) { 93 request.setAttribute("userMessage", "用户更新成功"); 94 userList(request, response);//通过servlet中listUser跳到用户列表 95 }else { 96 //更新失败跳转到修改页面 97 request.setAttribute("userMessage", "用户更新失败"); 98 request.setAttribute("userInfo", ud.findUser(Integer.valueOf(user.getUserId())));//这里回去是Admin对象 99 request.getRequestDispatcher(USEREDIT_PATH).forward(request, response); 100 } 101 } 102 103 public void userBatDel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 104 String ids=request.getParameter("ids"); 105 UserDao ud=new UserDaoImpl(); 106 107 if(ud.batDelUser(ids)) { 108 request.setAttribute("userMessage", "用户已批量删除"); 109 }else { 110 request.setAttribute("userMessage", "用户批量删除失败"); 111 } 112 //用户删除成功失败都跳转到用户列表页面 113 userList(request, response);//通过servlet中listUser跳到用户列表 114 } 115 }
不过这种写法,直接跳转jsp页面会报错,需要写一个String方法跳转
public String userAddjsp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { return USERADD_PATH; }