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会处理修改数据的请求。
其他的四种方法我就不一一列举了,大同小异,大家自己看一下。
Httpservlet源码说明的更多相关文章
- eclipse引入httpServlet源码
eclipse引入httpServlet源码 展开Apache Tomcat v7.0[Apache Tomcat v7.0] -> servlet-api.jar 找到 -> http ...
- 在eclipse中查看HttpServlet源码失败的解决方法
在初次建立java EE 项目时,想要查看HttpServlet源码时会提示失败, 按照网上的方式,将Tomcat中lib中的servlet-api.jar的包导进去,发现并不管用.并且提示里面并不包 ...
- HttpServlet源码分析
1.HttpServlet的用法 提供了创建Http Servlet的抽象类,通过实现此类定义自己的Servlet 2.HttpServlet是否是线程安全 先说结论:HttpServlet不是线程安 ...
- httpServlet,GenericServlet,Servlet源码分析
httpServlet源码: /* * Licensed to the Apache Software Foundation (ASF) under one or more * contribut ...
- 浅析Java源码之HttpServlet
纯粹是闲的,在慕课网看了几集的Servlet入门,刚写了1个小demo,就想看看源码,好在也不难 主要是介绍一下里面的主要方法,真的没什么内容啊~ 源码来源于apache-tomcat-7.0.52, ...
- HttpServlet中service方法的源码解读
前言 最近在看<Head First Servlet & JSP>这本书, 对servlet有了更加深入的理解.今天就来写一篇博客,谈一谈Servlet中一个重要的方法-- ...
- 深入理解 spring 容器,源码分析加载过程
Spring框架提供了构建Web应用程序的全功能MVC模块,叫Spring MVC,通过Spring Core+Spring MVC即可搭建一套稳定的Java Web项目.本文通过Spring MVC ...
- SpringMVC源码剖析(三)- DispatcherServlet的初始化流程
在我们第一次学Servlet编程,学Java Web的时候,还没有那么多框架.我们开发一个简单的功能要做的事情很简单,就是继承HttpServlet,根据需要重写一下doGet,doPost方法,跳转 ...
- SpringMVC源码剖析(四)- DispatcherServlet请求转发的实现
SpringMVC完成初始化流程之后,就进入Servlet标准生命周期的第二个阶段,即“service”阶段.在“service”阶段中,每一次Http请求到来,容器都会启动一个请求线程,通过serv ...
随机推荐
- C#中json字符串的序列化和反序列化
改文章转自:https://www.cnblogs.com/shang201215019/p/7907655.html 什么是 Json ? Json[javascript对象表示方法] ...
- SQL Server 跨服务器 不同数据库之间复制表的数据
不同数据库之间复制表的数据的方法: 当表目标表存在时: insert into 目的数据库..表 select * from 源数据库..表 当目标表不存在时: select * into 目的数据库 ...
- HDU - 4812 D Tree 点分治
http://acm.hdu.edu.cn/showproblem.php?pid=4812 题意:有一棵树,每个点有一个权值要求找最小的一对点,路径上的乘积mod1e6+3为k 题解:点分治,挨个把 ...
- How to have matlab tic toc in C++?
Reprinted form: https://stackoverflow.com/questions/13485266/how-to-have-matlab-tic-toc-in-c/1348558 ...
- HDU-4035-概率dp-期望-公式化简
Maze Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65768/65768 K (Java/Others)Total Submis ...
- curl使用记录
$header = array("Connection: Keep-Alive", "Accept: text/html,application/xhtml+xml,ap ...
- Fragment在Activity中跳转,实现类似新闻标题跳转新闻内容功能
1.准备的工作,新闻数据类,新闻数据适配器,适配器的布局: News.java package com.example.zps.fourfragmentbestpractice; /** * Crea ...
- Bayes' theorem (贝叶斯定理)
前言 AI时代的到来一下子让人感觉到数学知识有些捉襟见肘,为了不被这个时代淘汰,我们需要不断的学习再学习.其中最常见的就是贝叶斯定理,这个定理最早由托马斯·贝叶斯提出. 贝叶斯方法的诞生源于他生前为解 ...
- window 更新 nodejs
一直号称js程序员,结果发现自己机器的node版本才到 4.x.赶紧升级下. 在window下可以直接去nodejs.org下载最新的稳定版装上就行.同时也可以通过 powershell 命令行更新. ...
- linux命令返回值的含义
linux命令执行后无论成功与否都有一个返回值: 如果为 0,则表示命令执行成功,其它值则表示错误, 具体的错误码含义如下: "OS error code 1: Operation not ...