HttpSession session = req.getSession();
ServletContext servletContext = session.getServletContext();
ApplicationContext ctx = WebApplicationContextUtils
.getWebApplicationContext(servletContext);
serviceUser = (ServiceUser) ctx.getBean("serviceUser");
String action = (String) req.getParameter("actionName");
if ("login".equals(action)) {
session.removeAttribute("loginUser");
session.removeAttribute("users");
String username = (String) req.getParameter("username");
String password = (String) req.getParameter("password");
User user = serviceUser.login(username, password);
if (user != null) {
session.setAttribute("loginUser", user);
} else {
RequestDispatcher rd = getServletContext()
.getRequestDispatcher("/login.jsp");
rd.forward((ServletRequest) req, (ServletResponse) resp);
return;
}
} else if ("newUser".equals(action)) {
String username = (String) req.getParameter("username");
String password = (String) req.getParameter("password");
User user = new User();
user.setUsername(username);
user.setPassword(password);
try {
serviceUser.addUser(user);
session.setAttribute("newUser", true);
} catch (Exception e) {
e.printStackTrace();
session.setAttribute("newUser", false);
}
} else if ("removeUsers".equals(action)) {
String[] removeIds = req.getParameterValues("removeIds");
session.removeAttribute("newUser");
if (removeIds != null && removeIds.length > 0) {
int[] ids = new int[removeIds.length];
for (int i = 0; i < removeIds.length; i++) {
String is = removeIds[i];
int id = Integer.parseInt(is);
ids[i] = id;
}
try {
for (int id : ids) {
User user = serviceUser.getUser(id);
if ("admin".equals(user.getUsername())) {
continue;
}
serviceUser.deleteUser(user);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} else if ("changeUserMessage".equals(action)) {
session.removeAttribute("newUser");
try {
Object object = session.getAttribute("loginUser");
if (object instanceof User) {
User user = (User) object;
String password = (String) req.getParameter("password");
user.setPassword(password);
serviceUser.updateUser(user);
JSONObject json = new JSONObject();
JSONArray array = new JSONArray();
JSONObject member = null;
List<User> users = serviceUser.getUserAll();
for (User user2 : users) {
member = JSONObject.fromObject(user2);
array.add(member);
}
json.put("mydata", array);
PrintWriter pw = resp.getWriter();
pw.print(json.toString());
pw.close();
return;
}
} catch (Exception e) {
e.printStackTrace();
}
}
List<User> users = serviceUser.getUserAll();
session.setAttribute("users", users);
RequestDispatcher rd = getServletContext().getRequestDispatcher(
"/info.jsp");
rd.forward((ServletRequest) req, (ServletResponse) resp);