欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

javaee-servlet类源代码

程序员文章站 2022-04-23 17:50:42
...

贴贴源代码,心理就好受多了,哎,犯贱吗!javaee-servlet类源代码
            
    
    博客分类: javaee ServletContextServletConfigServletGenericServletHttpServlet 

 

ServletAPI 2.5的源代码

 

1.ServletContext就是我们经常说的application,不管是否常用,但总之是如雷贯耳。

 

 

package javax.servlet;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Set;

public abstract interface ServletContext
{
  public abstract String getContextPath();

  public abstract ServletContext getContext(String paramString);

  public abstract int getMajorVersion();

  public abstract int getMinorVersion();

  public abstract String getMimeType(String paramString);

  public abstract Set getResourcePaths(String paramString);

  public abstract URL getResource(String paramString)
    throws MalformedURLException;

  public abstract InputStream getResourceAsStream(String paramString);

  public abstract RequestDispatcher getRequestDispatcher(String paramString);

  public abstract RequestDispatcher getNamedDispatcher(String paramString);

  /**
   * @deprecated
   */
  public abstract Servlet getServlet(String paramString)
    throws javax.servlet.ServletException;

  /**
   * @deprecated
   */
  public abstract Enumeration getServlets();

  /**
   * @deprecated
   */
  public abstract Enumeration getServletNames();

  public abstract void log(String paramString);

  /**
   * @deprecated
   */
  public abstract void log(Exception paramException, String paramString);

  public abstract void log(String paramString, Throwable paramThrowable);

  public abstract String getRealPath(String paramString);

  public abstract String getServerInfo();

  public abstract String getInitParameter(String paramString);

  public abstract Enumeration getInitParameterNames();

  public abstract Object getAttribute(String paramString);

  public abstract Enumeration getAttributeNames();

  public abstract void setAttribute(String paramString, Object paramObject);

  public abstract void removeAttribute(String paramString);

  public abstract String getServletContextName();
}
 

 

2.接着是ServletConfig,用的真不多,就是从web.xml文件中提取参数。

 

   web.xml

 

<!-- begin -->
	<servlet>
		<servlet-name>ConfigTestServlet</servlet-name>
		<servlet-class>org.it315.ConfigTestServlet</servlet-class>
		<init-param>
			<param-name>firstname</param-name>
			<param-value>zhangsan-张三</param-value>
		</init-param>
		<init-param>
			<param-name>lastname</param-name>
			<param-value>lisi-李四</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>ConfigTestServlet</servlet-name>
		<url-pattern>/configTest</url-pattern>
	</servlet-mapping>
	<!--end  -->
 

 

   ServletConfig源代码

 

 

package javax.servlet;

import java.util.Enumeration;

public abstract interface ServletConfig
{
  public abstract String getServletName();

  public abstract ServletContext getServletContext();

  public abstract String getInitParameter(String paramString);

  public abstract Enumeration getInitParameterNames();
}

 

 

 

 

3.下面是Servlet的源代码(直接反编译来的,省的下载了),不管你知道不知道,你确一直在用

 

   只有在首次访问时,容器发现内存中没有当前servlet,才创建servlet对象。javaee-servlet类源代码
            
    
    博客分类: javaee ServletContextServletConfigServletGenericServletHttpServlet 单例吗?

 

  下面的init方法,在Servlet的整个生命周期内只被调用一次。

 

package javax.servlet;

import java.io.IOException;

public abstract interface Servlet
{
  public abstract void init(ServletConfig paramServletConfig)
    throws javax.servlet.ServletException;

  public abstract ServletConfig getServletConfig();

  public abstract void service(ServletRequest paramServletRequest, ServletResponse paramServletResponse)
    throws javax.servlet.ServletException, IOException;

  public abstract String getServletInfo();

  public abstract void destroy();
}
 

 

 

4.GenericServlet实现了Servlet, ServletConfig接口(Generic为通用之意)。同上,不管你知道不知道,你确一直在用

 

package javax.servlet;

import java.io.IOException;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.ResourceBundle;

public abstract class GenericServlet
  implements Servlet, ServletConfig, Serializable
{
  private static final String LSTRING_FILE = "javax.servlet.LocalStrings";
  private static ResourceBundle lStrings = ResourceBundle.getBundle("javax.servlet.LocalStrings");
  private transient ServletConfig config;

  public void destroy()
  {
  }

  public String getInitParameter(String name)
  {
    ServletConfig sc = getServletConfig();
    if (sc == null) {
      throw new IllegalStateException(lStrings.getString("err.servlet_config_not_initialized"));
    }

    return sc.getInitParameter(name);
  }

  public Enumeration getInitParameterNames()
  {
    ServletConfig sc = getServletConfig();
    if (sc == null) {
      throw new IllegalStateException(lStrings.getString("err.servlet_config_not_initialized"));
    }

    return sc.getInitParameterNames();
  }

  public ServletConfig getServletConfig()
  {
    return this.config;
  }

  public ServletContext getServletContext()
  {
    ServletConfig sc = getServletConfig();
    if (sc == null) {
      throw new IllegalStateException(lStrings.getString("err.servlet_config_not_initialized"));
    }

    return sc.getServletContext();
  }

  public String getServletInfo()
  {
    return "";
  }

  public void init(ServletConfig config)
    throws javax.servlet.ServletException
  {
    this.config = config;
    init();
  }

  public void init()
    throws javax.servlet.ServletException
  {
  }

  public void log(String msg)
  {
    getServletContext().log(getServletName() + ": " + msg);
  }

  public void log(String message, Throwable t)
  {
    getServletContext().log(getServletName() + ": " + message, t);
  }

  public abstract void service(ServletRequest paramServletRequest, ServletResponse paramServletResponse)
    throws javax.servlet.ServletException, IOException;

  public String getServletName()
  {
    ServletConfig sc = getServletConfig();
    if (sc == null) {
      throw new IllegalStateException(lStrings.getString("err.servlet_config_not_initialized"));
    }

    return sc.getServletName();
  }
}

 

5.HttpServlet,到这,知道人就多了,呵呵 。但除了doGet,doPost,service,其他从未用过。javaee-servlet类源代码
            
    
    博客分类: javaee ServletContextServletConfigServletGenericServletHttpServlet 

 

package javax.servlet.http;

import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.ResourceBundle;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public abstract class HttpServlet extends GenericServlet
  implements Serializable
{
  private static final String METHOD_DELETE = "DELETE";
  private static final String METHOD_HEAD = "HEAD";
  private static final String METHOD_GET = "GET";
  private static final String METHOD_OPTIONS = "OPTIONS";
  private static final String METHOD_POST = "POST";
  private static final String METHOD_PUT = "PUT";
  private static final String METHOD_TRACE = "TRACE";
  private static final String HEADER_IFMODSINCE = "If-Modified-Since";
  private static final String HEADER_LASTMOD = "Last-Modified";
  private static final String LSTRING_FILE = "javax.servlet.http.LocalStrings";
  private static ResourceBundle lStrings = ResourceBundle.getBundle("javax.servlet.http.LocalStrings");

  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
  {
    String protocol = req.getProtocol();
    String msg = lStrings.getString("http.method_get_not_supported");
    if (protocol.endsWith("1.1"))
      resp.sendError(405, msg);
    else
      resp.sendError(400, msg);
  }

  protected long getLastModified(HttpServletRequest req)
  {
    return -1L;
  }

  protected void doHead(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
  {
    NoBodyResponse response = new NoBodyResponse(resp);

    doGet(req, response);
    response.setContentLength();
  }

  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
  {
    String protocol = req.getProtocol();
    String msg = lStrings.getString("http.method_post_not_supported");
    if (protocol.endsWith("1.1"))
      resp.sendError(405, msg);
    else
      resp.sendError(400, msg);
  }

  protected void doPut(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
  {
    String protocol = req.getProtocol();
    String msg = lStrings.getString("http.method_put_not_supported");
    if (protocol.endsWith("1.1"))
      resp.sendError(405, msg);
    else
      resp.sendError(400, msg);
  }

  protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
  {
    String protocol = req.getProtocol();
    String msg = lStrings.getString("http.method_delete_not_supported");
    if (protocol.endsWith("1.1"))
      resp.sendError(405, msg);
    else
      resp.sendError(400, msg);
  }

  private Method[] getAllDeclaredMethods(Class c)
  {
    if (c.equals(HttpServlet.class)) {
      return null;
    }

    Method[] parentMethods = getAllDeclaredMethods(c.getSuperclass());
    Method[] thisMethods = c.getDeclaredMethods();

    if ((parentMethods != null) && (parentMethods.length > 0)) {
      Method[] allMethods = new Method[parentMethods.length + thisMethods.length];

      System.arraycopy(parentMethods, 0, allMethods, 0, parentMethods.length);

      System.arraycopy(thisMethods, 0, allMethods, parentMethods.length, thisMethods.length);

      thisMethods = allMethods;
    }

    return thisMethods;
  }

  protected void doOptions(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
  {
    Method[] methods = getAllDeclaredMethods(getClass());

    boolean ALLOW_GET = false;
    boolean ALLOW_HEAD = false;
    boolean ALLOW_POST = false;
    boolean ALLOW_PUT = false;
    boolean ALLOW_DELETE = false;
    boolean ALLOW_TRACE = true;
    boolean ALLOW_OPTIONS = true;

    for (int i = 0; i < methods.length; ++i) {
      Method m = methods[i];

      if (m.getName().equals("doGet")) {
        ALLOW_GET = true;
        ALLOW_HEAD = true;
      }
      if (m.getName().equals("doPost"))
        ALLOW_POST = true;
      if (m.getName().equals("doPut"))
        ALLOW_PUT = true;
      if (m.getName().equals("doDelete"))
        ALLOW_DELETE = true;

    }

    String allow = null;
    if ((ALLOW_GET) && 
      (allow == null)) allow = "GET";
    if (ALLOW_HEAD)
      if (allow == null) allow = "HEAD";
      else allow = allow + ", HEAD";
    if (ALLOW_POST)
      if (allow == null) allow = "POST";
      else allow = allow + ", POST";
    if (ALLOW_PUT)
      if (allow == null) allow = "PUT";
      else allow = allow + ", PUT";
    if (ALLOW_DELETE)
      if (allow == null) allow = "DELETE";
      else allow = allow + ", DELETE";
    if (ALLOW_TRACE)
      if (allow == null) allow = "TRACE";
      else allow = allow + ", TRACE";
    if (ALLOW_OPTIONS)
      if (allow == null) allow = "OPTIONS";
      else allow = allow + ", OPTIONS";

    resp.setHeader("Allow", allow);
  }

  protected void doTrace(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
  {
    String CRLF = "\r\n";
    String responseString = "TRACE " + req.getRequestURI() + " " + req.getProtocol();

    Enumeration reqHeaderEnum = req.getHeaderNames();

    while (reqHeaderEnum.hasMoreElements()) {
      String headerName = (String)reqHeaderEnum.nextElement();
      responseString = responseString + CRLF + headerName + ": " + req.getHeader(headerName);
    }

    responseString = responseString + CRLF;

    int responseLength = responseString.length();

    resp.setContentType("message/http");
    resp.setContentLength(responseLength);
    ServletOutputStream out = resp.getOutputStream();
    out.print(responseString);
    out.close();
  }

  protected void service(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
  {
    long lastModified;
    String method = req.getMethod();

    if (method.equals("GET")) {
      lastModified = getLastModified(req);
      if (lastModified == -1L)
      {
        doGet(req, resp);
      } else {
        long ifModifiedSince = req.getDateHeader("If-Modified-Since");
        if (ifModifiedSince < lastModified / 1000L * 1000L)
        {
          maybeSetLastModified(resp, lastModified);
          doGet(req, resp);
        } else {
          resp.setStatus(304);
        }
      }
    }
    else if (method.equals("HEAD")) {
      lastModified = getLastModified(req);
      maybeSetLastModified(resp, lastModified);
      doHead(req, resp);
    }
    else if (method.equals("POST")) {
      doPost(req, resp);
    }
    else if (method.equals("PUT")) {
      doPut(req, resp);
    }
    else if (method.equals("DELETE")) {
      doDelete(req, resp);
    }
    else if (method.equals("OPTIONS")) {
      doOptions(req, resp);
    }
    else if (method.equals("TRACE")) {
      doTrace(req, resp);
    }
    else
    {
      String errMsg = lStrings.getString("http.method_not_implemented");
      Object[] errArgs = new Object[1];
      errArgs[0] = method;
      errMsg = MessageFormat.format(errMsg, errArgs);

      resp.sendError(501, errMsg);
    }
  }

  private void maybeSetLastModified(HttpServletResponse resp, long lastModified)
  {
    if (resp.containsHeader("Last-Modified"))
      return;
    if (lastModified >= -3069086688014761984L)
      resp.setDateHeader("Last-Modified", lastModified);
  }

  public void service(ServletRequest req, ServletResponse res)
    throws ServletException, IOException
  {
    HttpServletRequest request;
    HttpServletResponse response;
    try
    {
      request = (HttpServletRequest)req;
      response = (HttpServletResponse)res;
    } catch (ClassCastException e) {
      throw new ServletException("non-HTTP request or response");
    }
    service(request, response);
  }
}
 

…………