Httpservlet源码说明

上一篇看了Servlet接口,现在来看下我们经常涉及的Httpservlet:

/**
 *
 * Provides an abstract class to be subclassed to create
 * an HTTP servlet suitable for a Web site. A subclass of
 * <code>HttpServlet</code> must override at least
 * one method, usually one of these:
 *
 * <ul>
 * <li> <code>doGet</code>, if the servlet supports HTTP GET requests
 * <li> <code>doPost</code>, for HTTP POST requests
 * <li> <code>doPut</code>, for HTTP PUT requests
 * <li> <code>doDelete</code>, for HTTP DELETE requests
 * <li> <code>init</code> and <code>destroy</code>,
 * to manage resources that are held for the life of the servlet
 * <li> <code>getServletInfo</code>, which the servlet uses to
 * provide information about itself
 * </ul>
 *
 * <p>There‘s almost no reason to override the <code>service</code>
 * method. <code>service</code> handles standard HTTP
 * requests by dispatching them to the handler methods
 * for each HTTP request type (the <code>do</code><i>XXX</i>
 * methods listed above).
 *
 * <p>Likewise, there‘s almost no reason to override the
 * <code>doOptions</code> and <code>doTrace</code> methods.
 *
 * <p>Servlets typically run on multithreaded servers,
 * so be aware that a servlet must handle concurrent
 * requests and be careful to synchronize access to shared resources.
 * Shared resources include in-memory data such as
 * instance or class variables and external objects
 * such as files, database connections, and network
 * connections.
 * See the
 * <a href="http://java.sun.com/Series/Tutorial/java/threads/multithreaded.html">
 * Java Tutorial on Multithreaded Programming</a> for more
 * information on handling multiple threads in a Java program.
 *
 * @author    Various
 */

public abstract class HttpServlet extends GenericServlet
    implements java.io.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(LSTRING_FILE);

HttpServlet是一个抽象类,它是为了实现http协议的servlet,所有继承此抽象类的servlet必须实现以下方法中的一种:

doGet;

doPost;

doPut;

doDelete;

init 和 destroy;

没有必要去重写service方法,service处理标准的http请求,根据不同的HTTP请求类型分发给以上的doXXX方法进行处理;

其他的描述和上一篇的servlet一样,在此就不多费篇幅咯。

下面重点看看doGet方法和doPost方法:

1、doGet:

    /**
     *
     * Called by the server (via the <code>service</code> method) to
     * allow a servlet to handle a GET request.
     *
     * <p>Overriding this method to support a GET request also
     * automatically supports an HTTP HEAD request. A HEAD
     * request is a GET request that returns no body in the
     * response, only the request header fields.
     *
     * <p>When overriding this method, read the request data,
     * write the response headers, get the response‘s writer or
     * output stream object, and finally, write the response data.
     * It‘s best to include content type and encoding. When using
     * a <code>PrintWriter</code> object to return the response,
     * set the content type before accessing the
     * <code>PrintWriter</code> object.
     *
     * <p>The servlet container must write the headers before
     * committing the response, because in HTTP the headers must be sent
     * before the response body.
     *
     * <p>Where possible, set the Content-Length header (with the
     * {@link javax.servlet.ServletResponse#setContentLength} method),
     * to allow the servlet container to use a persistent connection
     * to return its response to the client, improving performance.
     * The content length is automatically set if the entire response fits
     * inside the response buffer.
     *
     * <p>When using HTTP 1.1 chunked encoding (which means that the response
     * has a Transfer-Encoding header), do not set the Content-Length header.
     *
     * <p>The GET method should be safe, that is, without
     * any side effects for which users are held responsible.
     * For example, most form queries have no side effects.
     * If a client request is intended to change stored data,
     * the request should use some other HTTP method.
     *
     * <p>The GET method should also be idempotent, meaning
     * that it can be safely repeated. Sometimes making a
     * method safe also makes it idempotent. For example,
     * repeating queries is both safe and idempotent, but
     * buying a product online or modifying data is neither
     * safe nor idempotent.
     *
     * <p>If the request is incorrectly formatted, <code>doGet</code>
     * returns an HTTP "Bad Request" message.
     *
     *
     * @param req    an {@link HttpServletRequest} object that
     *            contains the request the client has made
     *            of the servlet
     *
     * @param resp    an {@link HttpServletResponse} object that
     *            contains the response the servlet sends
     *            to the client
     *
     * @exception IOException    if an input or output error is
     *                detected when the servlet handles
     *                the GET request
     *
     * @exception ServletException    if the request for the GET
     *                    could not be handled
     *
     *
     * @see javax.servlet.ServletResponse#setContentType
     *
     */

    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(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
    } else {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
    }
    }

^此方法由服务器调用允许一个servlet去处理一个GET请求;

^重写此方法去支持一个GET请求,同时也支持一个HEAD请求,一个HEAD请求是一个得到响应中没有返回任何主体的GET请求,只有请求头字段;

^当载入此方法时,读取请求数据,写入响应头,获取response的writer对象或者输出流对象,最终写入response数据,最好包含内容类型和编码方式;

^servlet容器必须在提交response之前写头文件,因为在HTTP协议中文件头必须在response body体之前提交;

^set方法是安全的,也就是说这个方法没有任何需要用户负责任的副作用;比如:大多数的查询都没有副作用,当你试图改变数据库的数据时,则需要使用其他方法。也就是说GET方法只用于查询某些简单的数据;

2、doPost方法:

  /**
     *
     * Called by the server (via the <code>service</code> method)
     * to allow a servlet to handle a POST request.
     *
     * The HTTP POST method allows the client to send
     * data of unlimited length to the Web server a single time
     * and is useful when posting information such as
     * credit card numbers.
     *
     * <p>When overriding this method, read the request data,
     * write the response headers, get the response‘s writer or output
     * stream object, and finally, write the response data. It‘s best
     * to include content type and encoding. When using a
     * <code>PrintWriter</code> object to return the response, set the
     * content type before accessing the <code>PrintWriter</code> object.
     *
     * <p>The servlet container must write the headers before committing the
     * response, because in HTTP the headers must be sent before the
     * response body.
     *
     * <p>Where possible, set the Content-Length header (with the
     * {@link javax.servlet.ServletResponse#setContentLength} method),
     * to allow the servlet container to use a persistent connection
     * to return its response to the client, improving performance.
     * The content length is automatically set if the entire response fits
     * inside the response buffer.
     *
     * <p>When using HTTP 1.1 chunked encoding (which means that the response
     * has a Transfer-Encoding header), do not set the Content-Length header.
     *
     * <p>This method does not need to be either safe or idempotent.
     * Operations requested through POST can have side effects for
     * which the user can be held accountable, for example,
     * updating stored data or buying items online.
     *
     * <p>If the HTTP POST request is incorrectly formatted,
     * <code>doPost</code> returns an HTTP "Bad Request" message.
     *
     *
     * @param req    an {@link HttpServletRequest} object that
     *            contains the request the client has made
     *            of the servlet
     *
     * @param resp    an {@link HttpServletResponse} object that
     *            contains the response the servlet sends
     *            to the client
     *
     * @exception IOException    if an input or output error is
     *                detected when the servlet handles
     *                the request
     *
     * @exception ServletException    if the request for the POST
     *                    could not be handled
     *
     *
     * @see javax.servlet.ServletOutputStream
     * @see javax.servlet.ServletResponse#setContentType
     *
     *
     */

    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(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
    } else {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
    }
    }

此时你会发现与上面的doGet方法的描述非常类似。唯一的不同是doPost会处理修改数据的请求。

其他的四种方法我就不一一列举了,大同小异,大家自己看一下。

时间: 2024-10-11 23:55:55

Httpservlet源码说明的相关文章

在eclipse中查看HttpServlet源码失败的解决方法

在初次建立java EE 项目时,想要查看HttpServlet源码时会提示失败, 按照网上的方式,将Tomcat中lib中的servlet-api.jar的包导进去,发现并不管用.并且提示里面并不包括HttpServlet源码. 因此,试着在Apache官方网站中下载对应的Tomcat的源码 然后在错误的页面添加下载好的包导入进去即可.

eclipse引入httpServlet源码

eclipse引入httpServlet源码 展开Apache Tomcat v7.0[Apache Tomcat v7.0] -> servlet-api.jar 找到 -> http -> HttpServlet 右键 servlet-api.jar -> properties -> Java Source Attachment -> 找到下载好的源码路径 源码地址 参考: http://blog.csdn.net/u013823429/article/detail

源码解析Servlet和HttpServlet

在编写 Servlet 时需要用到两个用于所有 Servlet 的基本软件包:javax.servlet 和 javax.servlet.http.下面主要介绍 javax.servlet 提供的 Servlet 以及 javax.servlet.http 提供的 HttpServlet 应用编程接口. Servlet源码: package javax.servlet; public interface Servlet {     public abstract void init(Servle

【Spring】DispatcherServlet源码分析

使用过HttpServlet的都应该用过其doGet和doPost方法,接下来看看DispatcherServlet对这两个方法的实现(源码在DispatcherServlet的父类FrameworkServlet中): @Override protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { proce

springmvc源码分析系列-请求处理流程

接上一篇-springmvc源码分析开头片 上一节主要说了一下springmvc与struts2的作为MVC中的C(controller)控制层的一些区别及两者在作为控制层方面的一些优缺点.今天就结合下面的一张图和上一篇中关于springmvc各个模块之间及各个模块中的类的继承关系的一张图对springmvc的请求处理流程进行一个分析.当然有了springmvc的请求处理流程我们就知道了springmvc是如何在启动的时候去加载或者去解析对应的具体控制器,以及modleAndView使干什么用的

Java微信公众平台开发模式+自定义按钮源码

首先,想用开放模式需要先成为开发者.成为开发者有两种写法. 一是:通过jsp页面,用out.print("echostr")//SHA1加密的字符串: 二是:通过Servlet.doGet返回exhostr,给微信平台. 这里我只写第二种方式的请求(这里的请求是以get方式请求),代码如下: import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.ut

springmvc源码解析-初始化

1.      概述 对于Web开发者,MVC模型是大家再熟悉不过的了,SpringMVC中,满足条件的请求进入到负责请求分发的DispatcherServlet,DispatcherServlet根据请求url到控制器的映射(HandlerMapping中保存),HandlerMapping最终返回HandlerExecutionChain,其中包含了具体的处理对象handler(也即我们编程时写的controller)以及一系列的拦截器interceptors,此时DispatcherSer

Servlet源码分析

Servlet API的核心就是javax.servlet.Servlet接口,所有的Servlet 类(抽象的或者自己写的)都必须实现这个接口.在Servlet接口中定义了5个方法,其中有3个方法是由Servlet 容器在Servlet的生命周期的不同阶段来调用的特定方法. 先看javax.servlet.servlet接口源码: Java代码 package javax.servlet;   //Tomcat源码版本:6.0.20 import java.io.IOException; pu

Servlet类源码说明

servlet是学习java web不可不懂的一个类,网上各种教程都参杂太多,每次理解都感觉像把别人吐出来的食物再放在嘴里咀嚼,小编一怒之下,直接打开源码,原汁原味的芬芳扑面而来: /** * Defines methods that all servlets must implement. * * <p>A servlet is a small Java program that runs within a Web server. * Servlets receive and respond