在之前的总结Java初试MVC及三层架构中,查看其目录结构仅仅对于User
对象的操作就写了6,7个servlet
,而每一个servlet
只对应一个功能,但随着以后项目的扩大,业务逻辑的复杂化,我们需要操作的对象不仅仅是一个User
类时,换句话说,我们操作数据库中的表不止一张时,那么可想而知我们的servlet需要写多少!
**思考:**我们能否像service
层和dao
层一样,将关于User
的操作都写在一个类当中,方便我们的使用呢。从而减少Servlet
的数量,现在是一个功能一个Servlet
,将其优化为一个模块一个Servlet
,相当于在数据库中一张表对应一个Servlet
,在Servlet
中提供不同的方法,完成用户的请求。
我们编写的所有servlet
都继承了HttpServlet
,与此同时都复写了doGet
以及doPost
方法。查看HttpServlet
源码,可以看见对doGet
以及doPost
的方法的调用都写在service
中。
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getMethod();
long lastModified;
if (method.equals("GET")) {
lastModified = this.getLastModified(req);
if (lastModified == -1L) {
this.doGet(req, resp);
} else {
long ifModifiedSince;
try {
ifModifiedSince = req.getDateHeader("If-Modified-Since");
} catch (IllegalArgumentException var9) {
ifModifiedSince = -1L;
}
if (ifModifiedSince < lastModified / 1000L * 1000L) {
this.maybeSetLastModified(resp, lastModified);
this.doGet(req, resp);
} else {
resp.setStatus(304);
}
}
} else if (method.equals("HEAD")) {
lastModified = this.getLastModified(req);
this.maybeSetLastModified(resp, lastModified);
this.doHead(req, resp);
} else if (method.equals("POST")) {
this.doPost(req, resp);
} else if (method.equals("PUT")) {