`
cfan_haifeng
  • 浏览: 122358 次
  • 性别: Icon_minigender_1
  • 来自: 郑州
社区版块
存档分类
最新评论

javaee-servlet类源代码

阅读更多

贴贴源代码,心理就好受多了,哎,犯贱吗!

 

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对象。单例吗?

 

  下面的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,其他从未用过。

 

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);
  }
}
 

…………

分享到:
评论

相关推荐

    JavaEE源代码 servlet-api

    JavaEE源代码 servlet-apiJavaEE源代码 servlet-apiJavaEE源代码 servlet-apiJavaEE源代码 servlet-apiJavaEE源代码 servlet-apiJavaEE源代码 servlet-apiJavaEE源代码 servlet-apiJavaEE源代码 servlet-apiJavaEE源...

    javaEE-servlet留言板项目demo,简单易懂,内附数据库和说明文档

    5. **项目结构**:典型的JavaEE项目结构可能包含`src/main/java`用于存放Java源代码(包括Servlet类),`src/main/webapp`存放Web应用资源,如JSP文件、静态资源(CSS、JavaScript)、WEB-INF目录下放置web.xml...

    javaee-ServletRequest 类相关源代码解析

    本文将深入解析ServletRequest类的相关源代码,帮助你理解其内部工作机制。 首先,ServletRequest接口位于javax.servlet包下,它是所有请求对象(如HttpServletRequest)的基础。它定义了一系列方法,如...

    ojdbc7jar+javaee-api-8.0.jar.rar

    标题中的"ojdbc7jar+javaee-api-8.0.jar.rar"是一个压缩包文件,包含两个关键组件:ojdbc7.jar和javaee-api-8.0.jar。这两个组件在Java开发和WebLogic服务器部署中扮演着重要角色。 1. **ojdbc7.jar**: ojdbc7.jar...

    JavaEE-Turorial-源码

    JavaEE-Turorial-源码 是一套专门为学习Java企业级应用开发提供的教程源代码,它与《JavaEE-Turorial-教材》配套使用,旨在帮助开发者深入理解JavaEE平台的各种技术,并通过实际操作来提升技能。JavaEE(Java ...

    3.3JavaEE-原生servlet_tomcat教师工资管理 (2).zip

    【文件名称】: "3.3JavaEE-原生servlet_tomcat教师工资管理.zip" 这个文件可能包含源代码、数据库配置、项目文档等资源,帮助用户理解和实现教师工资管理系统。 在这个项目中,关键知识点可能包括: 1. **Servlet...

    javaee_api.zip_JavaEE_Javaee的api_Javax.javaee-api_javaee api 文档_

    Servlet API定义了Servlet类和ServletConfig接口,以及Servlet生命周期相关的接口和方法。 2. **JSP**:JSP是Java EE中用于创建动态网页的技术,它允许开发者在HTML代码中嵌入Java代码。JSP页面会被编译为Servlet,...

    netbeans-8.0.2-javaee-windows

    - 对大型项目的支持更佳,即使处理大量源代码也能保持良好的性能。 6. **用户界面和自定义**: - 界面支持深色和浅色主题,可以根据个人喜好调整。 - 可自定义的快捷键和布局,适应不同用户的操作习惯。 - 多...

    javaEE源代码servlet框架

    在这个“javaEE源代码servlet框架”中,我们可以深入理解servlet的工作原理和配置方式。 1. **Servlet简介** Servlet是一个Java接口,由Java Servlet API定义。它提供了一组方法,使得开发者能够构建动态、交互式...

    javaee-SpringMVC-Mybatis 分页插件

    它提供了各种服务、API和协议,如Servlet、JSP、EJB等,帮助开发者快速开发服务器端应用程序。 2. **SpringMVC**:SpringMVC是Spring框架的一部分,是一个用于构建Web应用的模型-视图-控制器(MVC)架构。它简化了...

    javaEE-BBS项目

    此外,还有可能包含`src`目录,存放Java源代码,以及`lib`目录,用于存放项目依赖的库文件。 在实现JavaEE-BBS项目的过程中,开发者可能会遇到一些常见问题,例如安全性、性能优化、数据库设计、用户体验等。解决...

    毕业设计JAVAEE-原生servlet-ORACLE教务信息管理系统(源码+sql+文档+视频).rar

    学院号: 建筑学院 01 经济管理学院 02 土木水利学院 03 航空航天学院 04 信息科学技术学院 05 专业号: 建筑学:0101 城市规划:0102 景观设计:0103 会计:0201 金融 0202 市场营销 0203 ...

    JavaEE源代码 Servlet

    JavaEE源代码 ServletJavaEE源代码 ServletJavaEE源代码 ServletJavaEE源代码 ServletJavaEE源代码 ServletJavaEE源代码 ServletJavaEE源代码 ServletJavaEE源代码 ServletJavaEE源代码 ServletJavaEE源代码 ...

    javaee-kickoff-app.zip

    1. **项目结构**:JavaEE项目通常遵循Maven或Gradle的目录结构,包括`src/main/java`(源代码)、`src/main/resources`(资源文件)、`pom.xml`(Maven配置文件)或`build.gradle`(Gradle构建脚本)等。 2. **Web...

    javaEE-ssm框架开发源码

    - **Spring MVC配置文件**:通常为servlet-context.xml,定义了Spring MVC的拦截器、视图解析器等。 - **MyBatis配置文件**:mybatis-config.xml定义了MyBatis的全局配置,包括数据源、事务管理等。 - **Mapper接口...

    javaEE-api.zip

    1. **Servlet**:Servlet是JavaEE中处理HTTP请求的核心组件,它扩展了服务器的功能,允许我们编写运行在服务器端的Java代码来处理客户端的请求。 2. **JSP(JavaServer Pages)**:JSP是一种动态网页技术,它将HTML...

    javaEE-原生Servlet-SqlServer医院管理住院系统的研究与实现(源码+数据库sql+lun文+视频)

    医院管理系统的源代码和论文由学员提供.... 本系统主要分为六大模块,分别是医生管理模块、病人管理模块、病床管理模块、收费管理模块、统计分析模块和系统功能模块 ,医生、病人和医院的管理人员都可以通过此...

    软件工程专业计算机专业javaEE-原生Servlet-MySql企业财务管理系统设计与实现(源码+数据库sql+视频齐全)

    这个系统不仅提供了完整的源代码,还包括了数据库SQL脚本和配套的教学视频,使得学习者能够全方位地理解和掌握相关技术。 首先,JavaEE是企业级应用开发的主流平台,它包含了Servlet技术,用于处理HTTP请求和响应。...

    JavaEE源代码 ServletExample

    JavaEE源代码 ServletExampleJavaEE源代码 ServletExampleJavaEE源代码 ServletExampleJavaEE源代码 ServletExampleJavaEE源代码 ServletExampleJavaEE源代码 ServletExampleJavaEE源代码 ServletExampleJavaEE源...

    JavaEE项目案例源代码3

    【JavaEE项目案例源代码3】是一个典型的Java企业级应用示例,主要展示了如何使用JSP(JavaServer Pages)和Servlet技术构建一个信息发布平台。在这个案例中,开发者将学习到如何利用JavaEE的核心组件来实现动态网页...

Global site tag (gtag.js) - Google Analytics