/** 获取用户列表数据 */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 设置编码-解决中文乱码 resp.setCharacterEncoding("utf-8"); UserService userService = new UserService(); List<User> users = userService.getAllUser(); Gson gson = new Gson(); String userJson = gson.toJson(users); // 将List<User>集合中的User转换成json格式的字符串数据 // System.out.println(userJson); // 将json格式的用户列表返回的浏览器端 PrintWriter out = resp.getWriter(); out.write(userJson); }
/** 处理登录请求 */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /** 用户服务 */ UserService userService = new UserService(); String username = (String) req.getParameter("username"); String password = req.getParameter("password"); User user = userService.login(username, password); if (user == null) { // 登录失败,跳转到登录页面 req.setAttribute("error", "用户名或密码错误!"); req.getRequestDispatcher("/login.jsp").forward(req, resp); // 请求转发 } else { // 登录成功,跳转到成功页面 // 登录成功,将用户信息放入session中 HttpSession session = req.getSession(); session.setAttribute("user", user); resp.sendRedirect(req.getContextPath() + "/users.jsp"); } }