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 ...
随机推荐
- The web application you are attempting to access on this web server is currently unavailable.......
今天去服务器安装了个.net 4.0 framework(原本有1.0和2.0的),配置好站点后,选择版本为4.0,访问出错,错误代码如下 Server Application Unavailable ...
- WebApi用Post的方式提交Json时,获取不到值或不进对应方法的问题
又是一个通宵,终于搞明白了. 被WebApi坑得好惨. 之前用各种方法Post上来,有时可以读到结构,但没值,有时直接就是一个Null,有时连方法都没进就跑了,只是来控制器里看了一下…… 最后好友说还 ...
- java应用简单递归
毕业后就怎么学过算法,还在上学的时候学过数据结构,现在基本上都还给老师了,可惜老师学费没有还给我... 情景: 类似于给定一个数字,算他由多少个数字组成,比如:36 现在有10.5.1 ,那么最佳帅3 ...
- JS在项目中用到的AOP, 以及函数节流, 防抖, 事件总线
1. 项目中在绑定事件的时候总想在触发前,或者触发后做一些统一的判断或逻辑,在c#后端代码里,可以用Attribute, filter等标签特性实现AOP的效果,可是js中没有这种用法,归根到本质还是 ...
- Java中替换字符串中特殊字符+ 20150921
需求:今天需要将字符串中的" +"转换程"%2B",但是"+"是正则表达式中的特殊字符,使用需要反斜杠转义,具体示范: String a=& ...
- DataReader使用
一.DataReader含义 DataReader相比于DataSet,DataReader是一个抽象类,所以不能用DataReader DR = new DataReader(),来构造函数创建对象 ...
- DesignPattern(五)行为型模式(上)
行为型模式 行为型模式是对在不同对象之间划分责任和算法的抽象化.行为模式不仅仅关于类和对象,还关于它们之间的相互作用.行为型模式又分为类的行为模式和对象的行为模式两种. 类的行为模式——使用继承关系在 ...
- Install LAMP Server (Apache, MariaDB, PHP) On CentOS/RHEL/Scientific Linux 7
Install LAMP Server (Apache, MariaDB, PHP) On CentOS/RHEL/Scientific Linux 7 By SK - August 12, 201 ...
- Hadoop序列化机制及实例
序列化 1.什么是序列化?将结构化对象转换成字节流以便于进行网络传输或写入持久存储的过程.2.什么是反序列化?将字节流转换为一系列结构化对象的过程.序列化用途: 1.作为一种持久化格式. 2.作为一种 ...
- 64位windows 2003和windows xp
msdn windows2003 64位简体中文企业版R2 sp2(cn_win_srv_2003_r2_enterprise_x64_with_sp2_vl) ed2k://|file|cn_win ...