上一篇看了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会处理修改数据的请求。

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

Httpservlet源码说明的更多相关文章

  1. eclipse引入httpServlet源码

    eclipse引入httpServlet源码 展开Apache Tomcat v7.0[Apache Tomcat v7.0] -> servlet-api.jar 找到 -> http ...

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

    在初次建立java EE 项目时,想要查看HttpServlet源码时会提示失败, 按照网上的方式,将Tomcat中lib中的servlet-api.jar的包导进去,发现并不管用.并且提示里面并不包 ...

  3. HttpServlet源码分析

    1.HttpServlet的用法 提供了创建Http Servlet的抽象类,通过实现此类定义自己的Servlet 2.HttpServlet是否是线程安全 先说结论:HttpServlet不是线程安 ...

  4. httpServlet,GenericServlet,Servlet源码分析

    httpServlet源码:   /* * Licensed to the Apache Software Foundation (ASF) under one or more * contribut ...

  5. 浅析Java源码之HttpServlet

    纯粹是闲的,在慕课网看了几集的Servlet入门,刚写了1个小demo,就想看看源码,好在也不难 主要是介绍一下里面的主要方法,真的没什么内容啊~ 源码来源于apache-tomcat-7.0.52, ...

  6. HttpServlet中service方法的源码解读

    前言     最近在看<Head First Servlet & JSP>这本书, 对servlet有了更加深入的理解.今天就来写一篇博客,谈一谈Servlet中一个重要的方法-- ...

  7. 深入理解 spring 容器,源码分析加载过程

    Spring框架提供了构建Web应用程序的全功能MVC模块,叫Spring MVC,通过Spring Core+Spring MVC即可搭建一套稳定的Java Web项目.本文通过Spring MVC ...

  8. SpringMVC源码剖析(三)- DispatcherServlet的初始化流程

    在我们第一次学Servlet编程,学Java Web的时候,还没有那么多框架.我们开发一个简单的功能要做的事情很简单,就是继承HttpServlet,根据需要重写一下doGet,doPost方法,跳转 ...

  9. SpringMVC源码剖析(四)- DispatcherServlet请求转发的实现

    SpringMVC完成初始化流程之后,就进入Servlet标准生命周期的第二个阶段,即“service”阶段.在“service”阶段中,每一次Http请求到来,容器都会启动一个请求线程,通过serv ...

随机推荐

  1. css强制html不换行 css强制英文单词断行 重拾丢失的

    css强制html不换行 css强制英文单词断行 强制不换行 div{ white-space:nowrap; } 自动换行 div{ word-wrap: break-word; word-brea ...

  2. Wannafly挑战赛15-C-出队

    链接:https://www.nowcoder.com/acm/contest/112/C来源:牛客网 约瑟夫问题(https://baike.baidu.com/item/约瑟夫问题),n个人,1 ...

  3. UVA-10603 Fill (BFS)

    题目大意:有三个已知体积但不知刻度的杯子,前两个杯子中初始时没有水,第三个装满水,问是否可以倒出d升水,如果倒不出,则倒出一个最大的d’,使得d’<=d,并且在这个过程中要求总倒水量最少. 题目 ...

  4. 谈谈oracle里的join、left join、right join、full join-版本2

    --1.left join  左表为主表,左表返回全部数据,右表只返回与左表相匹配的数据select   t1.fpdm,t1.fphm ,t1.zjr,t1.zjsj,t1.zjjx,t1.zjje ...

  5. git 忽略不提交的文件3种情形

    1..gitignore文件 :从未提交过的文件,从来没有被 Git 记录过的文件 也就是添加之后从来没有提交(commit)过的文件,可以使用.gitignore忽略该文件.只能作用于未跟踪的文件( ...

  6. mouseover、mouseout和mouseenter、mouseleave

    这里直接把<Javascript 高级程序设计(第三版)>中的解释贴出来: mouseover:在鼠标指针位于一个元素外部,然后用户将其首次移入另一个元素边界之内时触发.不能通过键盘触发这 ...

  7. PHP Startup: Unable to load dynamic library '/usr/lib64/php/modules/phalcon.so' - /usr/lib64/php/mod

    这个警告可能是,扩展在php.d里面加载了一遍,然后又在php.ini里写了一遍导致的

  8. 是用TOP关键字对COUNT性能优化

    在对大数据量进行检索或者分页的时候需要计算命中记录数大小,一般情况下我们可以直接COUNT得到结果,但是当结果集很大的时候(比如1万以上)具体结果值已经不重要了.没有人真的翻阅1万条记录,比如百度,你 ...

  9. CentOS6下yum升级安装mysql

    CentOS6默认版本的mysql是5.1.73,当前主流版本一般为mysql-5.6,需要安装该版本的话可以执行以下操作 1.1.卸载旧版mysql 1)备份数据 # 直接删除老版本的相关文件可能会 ...

  10. Element-ui实现loading的局部刷新

    后台管理系统loading的局部刷新 在一次vue+element-ui后台管理系统的项目中,遇到这样一个问题,引入element-ui加载框后,loading会占满整个屏幕,虽然通过改变路由实现了局 ...