zoukankan      html  css  js  c++  java
  • Servlet , GenericServlet和HttpServlet

    Servlet是一套规范,表现为一套接口,留给开发人员去实现,Servlet接口定义如下(附加servlet-api source来查看源码)

    其中init方法被Servlet容器调用,servlet容器就是比如说Tomcat Server中的Service中的Connector和Container中的Container。

     1 public interface Servlet {
     2 
     3     public void init(ServletConfig config) throws ServletException;
     4    
     5 
     6     public ServletConfig getServletConfig();
     7     
     8 
     9     public void service(ServletRequest req, ServletResponse res)
    10     throws ServletException, IOException;
    11 
    12     public String getServletInfo();
    13 
    14     public void destroy();
    15 }

    其中还有一个很重要的一个接口ServletConfig, 实现该接口必须实现如下方法: 这些方法是有关获取Servlet参数和ServletContext的。Servlet参数如何传递呢, 可以在web.xml中通过init-param传递参数,这个参数就是通过ServletConfig来保存的,ServletContext代表应用本身,整个应用都可以访问到。ServletConfig中保存的参数是Servlet级别的,ServletContext则是应用级的。

    比如使用Spring的时候,一般会设置applicationContext.xml的路径,通常就是在context-param里设置contextConfigLocation。而Spring MVC中设置的参数则是在init-param中,这是Servlet级别的,存在ServletConfig中。

     1 public interface ServletConfig {
     2 
     3 
     4     public String getServletName();
     5 
     6     public ServletContext getServletContext();
     7 
     8     public String getInitParameter(String name);
     9 
    10     public Enumeration getInitParameterNames();
    11 
    12 }

    GenericServlet是Servlet的默认实现,该类还实现了ServletConfig方法。它帮我们做了一些事儿,比如我们可以直接getServletContext。而不用getServletConfig().getServletContext();因为该方法内部帮我们做了这个操作。另外还帮我们做了一个无参init方法,无参init被实现的有参init方法调用,有参init方法中实现如下,这可以帮我们不关注config赋值,让子类重写init变得纯粹

    ,只处理我们自己的业务逻辑。如果重写了有参init方法,要记得调用super.init(config), 这样为config赋值。其实也没有必要重写这个了~

    1  public void init(ServletConfig config) throws ServletException {
    2     this.config = config;
    3     this.init();
    4     }

    HttpServlet是和协议相关的实现,它继承了GenericServlet,实现中丰富了service方法,将ServletRequest和ServletResponse转换为HttpServletRequest和HttpServletResponse,并将不同的请求类型路由到不同的处理方法中。因为后者接口继承了前者。

    HttpServletRequest extends ServletRequest 

    public class HttpServletRequestWrapper extends ServletRequestWrapper implements HttpServletRequest

  • 相关阅读:
    斐波那契数列相关
    社论CF1616G
    题解AGC056
    IOI2018 meetings
    题解UOJ#696. 【候选队互测2022】理论复杂度
    larval5.1模型静态使用多次出现查询属性信息存在问题
    SQL Server里面可能经常会用到的日期格式转换方法
    asp.net页面刷新后样式就发生了改变
    [武汉站]Windows 7 社区发布活动
    C++/CLI学习入门数组
  • 原文地址:https://www.cnblogs.com/tdws/p/4077744.html
Copyright © 2011-2022 走看看