SpringMvc 中 FrameworkServlet 覆盖 service 的有点。

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

   HttpMethod httpMethod = HttpMethod.resolve(request.getMethod());
   if (httpMethod == HttpMethod.PATCH || httpMethod == null) {
      processRequest(request, response);
   }
   else {
      super.service(request, response);
   }
}
@Override
protected final void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

processRequest(request, response);
}

@Override
protected final void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

processRequest(request, response);
}

 

先上代码。

可以看到,最终调用了super.service,然后又覆盖了 doGet、doPost等方法。

1、为什么最后都调用了 processRequest ?

在HttpServlet中,最开始是按类型将请求分开的。但是,SpringMVC又将他们统一用  processRequest  来处理,是因为springmvc是将不同类型请求用不同的Handler来处理。

2、为什么不直接覆盖 HttpServlet,而是调用了super.service ?

现在看来结构是没有问题的。但是,如果后续扩展时想在 doPost请求之前做一些处理。。。这是,方案为覆盖 dispatcherServlet 的doPost方法, 在里边先进行一些处理,然后再调用 super.doPost。但是父类根本没调用 doPost,所以就出现问题了。这问题解决方法也很简单。但是正常逻辑 doPost 应该可以解决才对。

所以springMvc这种做法看似笨拙但是是很有必要的。

 

posted @ 2018-03-30 09:31  剑神西门吹雪  阅读(867)  评论(0编辑  收藏  举报