/**
* 用户管理Servlet
*/
@WebServlet("/user.do")
public class UserServlet extends HttpServlet {
//生成模拟数据初始化
@Override
public void init() throws ServletException {
User user = new User();
user.setUserid(1);
user.setUsername("Oldlu");
user.setUsersex("male");
user.setUserbirth(new Date());
User user2 = new User();
user2.setUserid(2);
user2.setUsername("Kevin");
user2.setUsersex("male");
user2.setUserbirth(new Date());
List<User> list = new ArrayList<>();
list.add(user);
list.add(user2);
ServletContext servletContext = this.getServletContext();
servletContext.setAttribute("list",list);
}
@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 flag = req.getParameter("flag");
if("getData".equals(flag)){
this.getData(req,resp);
}else if("addUser".equals(flag)){
this.addUser(req,resp);
}else if("updateUser".equals(flag)){
this.updateUser(req,resp);
}else{
this.deleteUser(req,resp);
}
}
//获取页面初始化数据
private void getData(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<User> list = (List<User>) this.getServletContext().getAttribute("list");
String s = JsonUtils.objectToJson(list);
resp.setContentType("application/json");
PrintWriter pw = resp.getWriter();
pw.print(s);
pw.flush();
pw.close();
}
}