首先先随便聊一聊,前端提供的参数必须和domain中的类以及数据库中的列标题一致,否则经过javabean,可能会丢失结果。
public class CustomerServlet extends BaseServlet {
//依赖service层
private CustomerService customerService=new CustomerService();
//添加用户服务
public String add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//首先需要把request域中的参数封装到Customer类中
Customer c= CommonUtils.toBean(request.getParameterMap(), Customer.class);
c.setCid(CommonUtils.uuid());
System.out.println(c.getCname());
//然后调用service的add方法
customerService.add(c);
//给request域中的msg添加内容
request.setAttribute("msg", "添加用户成功!");
//返回给BaseServlet,让其做转发工作
return "f:/msg.jsp";
}
//查询客服服务
public String findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//创建结果集,调用service中findAll方法
List<Customer> res=new ArrayList<>();
res=customerService.findAll();
//将结果集放在request域中,由BaseServlet来完成表单显示
request.setAttribute("cstmList", res);
//告诉BaseServlet转发给list.jsp
return "/list.jsp";
}
//根据Cid加载用户
public String preEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//首先需要获得cid
String cid=request.getParameter("cid");
//然后调用Service中的load方法,通过cid找到用户
Customer c=customerService.load(cid);
//然后将用户保存到request域中的cstm
request.setAttribute("cstm", c);
//告诉BaseServlet用户已经加载好了,可以转发到edit.jsp中
return "f:/edit.jsp";
}
//编辑用户
public String edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//首先获得request域中的参数,封装到Customer类中
Customer c=CommonUtils.toBean(request.getParameterMap(), Customer.class);
//然后调用Service中的edit方法
customerService.edit(c);
//将编辑成功的消息放入request域中
request.setAttribute("msg", "恭喜!编辑成功");
//告诉BaseServlet转发到msg.jsp
return "f:/msg.jsp";
}
//实现查询方法
public String query(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//首先需要将request域中的信息封装到customer类中
Customer c=CommonUtils.toBean(request.getParameterMap(), Customer.class);
//然后调用Service中的query方法
//最后把List<customer>放在request域中
request.setAttribute("cstmList", customerService.query(c));
//告诉BaseServlet转发到list.jsp
return "/list.jsp";
}
}
然后聊一聊,Servlet层,首先为了让一个Servlet能够处理多个请求,可以用BaseServlet的方法来实现,BaseServlet来处理和前端的各种交互,我们自己的Servlet继承BaseServlet,前端在URL中加入参数,通过参数来确定service中需要处理的方法,只后我们自己的Servlet通过传递字符串的方式来告诉BaseServlet怎么响应请求。
之后就是前端的一些细节,略过。