Servlet--HttpServlet类

2024-06-17 11:48
文章标签 servlet httpservlet

本文主要是介绍Servlet--HttpServlet类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

  • HttpServlet类
定义
public class HttpServlet extends GenericServlet implements Serializable

这是一个抽象类,用来简化 HTTP Servlet 写作的过程。它是 GenericServlet 类的扩充,提供了一个处理 HTTP 协议的框架。在这个类中的 service 方法支持例如 GET、POST 这样的标准的 HTTP 方法。这一支持过程是通过分配他们到适当的方法(例如 doGet、doPost)来实现的。


方法
1、doDelete

protected void doDelete(HttpServletRequest request,HttpServletResponse response) 

throws ServletException,IOException;

被这个类的 service 方法调用,用来处理一个 HTTP DELETE 操作。这个操作允许客户端请求从服务器上删除 URL。这一操作可能有负面影响,对此用户就负起责任。这一方法的默认执行结果是返回一个HTTP BAD_REQUEST 错误。 当你要处理 DELETE
请求时,你必须重载这一方法。
2、doGet

protected void doGet(HttpServletRequest request,HttpServletResponse response) 

throws ServletException,IOException;

被这个类的 service 方法调用,用来处理一个 HTTP GET 操作。这个操作允许客户端简单地从一个 HTTP 服务器“获得”资源。对这个方法的重载将自动地支持 HEAD 方法。GET 操作应该是安全而且没有负面影响的。这个操作也应该可以安全地重复。这一方法的默认执行结果是返回一个 HTTP BAD_REQUEST 错误。
3、doHead

protected void doHead(HttpServletRequest request,HttpServletResponse response) 

throws ServletException,IOException;

被这个类的 service 方法调用,用来处理一个 HTTP HEAD 操作。默认的情况是,这个操作会按照一个无条件的 GET 方法来执行,该操作不向客户端返回任何数据,而仅仅是返回包含内容长度的头信息。与 GET 操作一样,这个操作应该是安全而且没有负面影响的。这个操作也应该可以安全地重复。这个方法的默认执行结果是自动处理 HTTP HEAD 操作, 这个方法不需要被一个子类执行。
4、doOptions

protected void doOptions(HttpServletRequest request,HttpServletResponse response) 

throws ServletException,IOException;

被这个类的 service 方法调用,用来处理一个 HTTP OPTION 操作。这个操作自动地决定支持哪一种 HTTP 方法。例如,一个 Servlet 写了一个 HttpServlet 的子类并重载了 doGet方法,doOption 会返回下面的头:Allow:GET,HEAD,TRACE,OPTIONS
你一般不需要重载这个方法。
5、doPost

protected void doPost(HttpServletRequest request,HttpServletResponse response) 

throws ServletException,

IOException;
被这个类的 service 方法调用, 用来处理一个 HTTP POST 操作。 这个操作包含请求体的数据,Servlet 应该按照他行事。这个操作可能有负面影响。例如更新存储的数据或在线购物。这一方法的默认执行结果是返回一个 HTTP BAD_REQUEST 错误。当你要处理 POST操作时,你必须在 HttpServlet 的子类中重载这一方法。
6、doPut

protected void doPut(HttpServletRequest request,HttpServletResponse response) 

throws ServletException,IOException;

被这个类的 service 方法调用, 用来处理一个 HTTP PUT 操作。 这个操作类似于通过 FTP发送文件。这个操作可能有负面影响。例如更新存储的数据或在线购物。这一方法的默认执行结果是返回一个 HTTP BAD_REQUEST 错误。当你要处理 PUT 操
作时,你必须在 HttpServlet 的子类中重载这一方法。
7、doTrace

protected void doTrace(HttpServletRequest request,HttpServletResponse response)

 throws ServletException,IOException;

被这个类的 service 方法调用,用来处理一个 HTTP TRACE 操作。这个操作的默认执行结果是产生一个响应,这个响应包含一个反映 trace 请求中发送的所有头域的信息。当你开发 Servlet 时,在多数情况下你需要重载这个方法。
8、getLastModified
protected long getLastModified(HttpServletRequest request);
返回这个请求实体的最后修改时间。为了支持 GET 操作,你必须重载这一方法,以精确地反映最后修改的时间。 这将有助于浏览器和代理服务器减少装载服务器和网络资源, 从而更加有效地工作。返回的数值是自 1970-1-1 日(GMT)以来的毫秒数。默认的执行结果是返回一个负数,这标志着最后修改时间未知,它也不能被一个有条件的GET 操作使用。
9、service

protected void service(HttpServletRequest request,HttpServletResponse response)

 throws ServletException,IOException;

public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException;

这是一个 Servlet 的 HTTP-specific 方案, 它分配请求到这个类的支持这个请求的其他方法。当你开发 Servlet 时,在多数情况下你不必重载这个方法。实际开发中需要重载的就是doGet和doPost这2个方法。然后一般都是重写doPost方法,然后重写doGet的时候只需要调下doPost方法即可。下面贴出HttpServlet类的源码。

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 GenericServletimplements 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);elseresp.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);elseresp.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);elseresp.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);elseresp.sendError(400, msg);}private static 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"; elseallow = allow + ", HEAD";if (ALLOW_POST)if (allow == null) allow = "POST"; elseallow = allow + ", POST";if (ALLOW_PUT)if (allow == null) allow = "PUT"; elseallow = allow + ", PUT";if (ALLOW_DELETE)if (allow == null) allow = "DELETE"; elseallow = allow + ", DELETE";if (ALLOW_TRACE)if (allow == null) allow = "TRACE"; elseallow = allow + ", TRACE";if (ALLOW_OPTIONS) {if (allow == null) allow = "OPTIONS"; elseallow = 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{String method = req.getMethod();if (method.equals("GET")) {long 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")) {long 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 >= 0L)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);}
}


这篇关于Servlet--HttpServlet类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1069362

相关文章

JavaWeb系列六: 动态WEB开发核心(Servlet) 上

韩老师学生 官网文档为什么会出现Servlet什么是ServletServlet在JavaWeb项目位置Servlet基本使用Servlet开发方式说明快速入门- 手动开发 servlet浏览器请求Servlet UML分析Servlet生命周期GET和POST请求分发处理通过继承HttpServlet开发ServletIDEA配置ServletServlet注意事项和细节 Servlet注

玩转Web之servlet(三)---一张图看懂B/S架构

学WEB, 首先 要明白B/S架构,本文将简单说一下小编的愚见,若有不当,欢迎大家指正。 首先,什么是B/S架构?B/S是Broweser/Server的缩写,即浏览器/服务器模式,简单说就是客户端使用浏览器,服务端使用Web服务器,客户端与服务端之间使用http协议进行通讯。 那么,为什么要使用B/S架构呢?当然是其有一定的优点:           1.传统的C/S架构 需要单独安装客户

jsp和Servlet中的响应(response)编码

<span style="font-size:18px;">  常见字符编码:iso-8859-1(不支持中文)、gb2312、gbk、gb18030(系统默认编码,中国的国标码)、utf-8(万国码,支持全世界的编码,所以我们使用这个)1. 响应编码* 当使用response.getWriter()来向客户端发送字符数据时,如果在之前没有设置编码,那么默认使用iso,因为iso不支持中文

Servlet小记

Servlet中的方法大多数不由我们来调用,而是由Tomcat来调用。并且Servlet的对象也不由我们来创建,由Tomcat来创建! 在web.xml中配置Servlet的目的其实只有一个,就是把访问路径与一个Servlet绑定到一起。 服务器会在Servlet第一次被访问时创建Servlet,或者是在服务器启动时创建Servlet。如果服务器启动时就创建Servlet,那么还需要在we

Jsp和Servlet分工之求a+b的和

流程: 在WebContent文件下面建立sum文件夹,再在这里面新建form.jsp和result.jsp页面,在 form.jsp: <body> <span style="white-space:pre"> </span>//是项目名加资源路径<form action="/Web/SumServlet" method="post">整数a:<input type="

WEB服务器、应用服务器、Tomcat、Servlet

Web服务器:专门处理HTTP请求,提供WEB信息浏览服务 应用服务器:可解析运行后台代码,为应用服务器提供商业逻辑 Servlet:是一种运行在支持Java语言的服务器上的组件 Tomcat是一个Servlet容器,也是具备WEB服务器能力的轻量级的应用服务器

servlet---java读取本地文件

元素顺序列表:       元素标签详解: 元素1:<icon> 含义 icon元素包含small-icon和large-icon两个子元素.用来指定web站台中小图标和大图标的路径. <small-icon>/路径/smallicon.gif</small-icon> small-icon元素应指向web站台中某个小图标的路径,大小为16 X 16 pixel,但是图象

web容器 web服务器 servlet/jsp容器 之间的区别和关系

Web服务器(软件): Apache http server, 这个它的网址,http://httpd.apache.org/download.cgi#apache24,实现的是HTTP协议,提供的是静态网页服务。 替代者有Nginx Web容器: tomcat, http://tomcat.apache.org/whoweare.html, 实现的是JSP,Servlet,提供了环境

深入理解Servlet Filter及其限流实践

引言 在Java Servlet技术中,Filter是一个拦截器,它允许开发者在请求到达目标资源之前或响应发送给客户端之后,对请求或响应进行拦截和处理。这种机制为实现诸如身份验证、日志记录、请求修改等功能提供了极大的灵活性。 Filter基础 Filter接口定义了三个主要方法:init()、doFilter()和destroy()。下面我们将逐一介绍这些方法的作用和使用场景。 init(

java jsp+servlet实现登录网页设计

java jsp+servlet实现登录网页设计 这次涉及到四个文件: 登录页面:login.jsp 登录成功欢迎页面:success.jsp 登录失败页面:fail.jsp Servlet处理文件:LoginServlet.java 其实还涉及到一个文件:web.xml,这个后面再说: 下面分别介绍这几个文件: //------------------