2021-2022赛季 软191级队学习资料

J2EE编程之重点API(基础包)

Servlet

英文简介
public interface Servlet

Defines methods that all servlets must implement.

A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol.

To implement this interface, you can write a generic servlet that extends javax.servlet.GenericServlet or an HTTP servlet that extends javax.servlet.http.HttpServlet.

This interface defines methods to initialize a servlet, to service requests, and to remove a servlet from the server. These are known as life-cycle methods and are called in the following sequence:

  1. The servlet is constructed, then initialized with the init method.
  2. Any calls from clients to the service method are handled.
  3. The servlet is taken out of service, then destroyed with the destroy method, then garbage collected and finalized.

In addition to the life-cycle methods, this interface provides the getServletConfig method, which the servlet can use to get any startup information, and the getServletInfo method, which allows the servlet to return basic information about itself, such as author, version, and copyright.

中文简介

定义所有 servlet 都必须实现的方法。

servlet 是运行在 Web 服务器中的小型 Java 程序。servlet 通常通过 HTTP(超文本传输协议)接收和响应来自 Web 客户端的请求。

要实现此接口,可以编写一个扩展 javax.servlet.GenericServlet 的一般 servlet,或者编写一个扩展 javax.servlet.http.HttpServlet 的 HTTP servlet。

此接口定义了初始化 servlet 的方法、为请求提供服务的方法和从服务器移除 servlet 的方法。这些方法称为生命周期方法,它们是按以下顺序调用的:

  1. 构造 servlet,然后使用 init 方法将其初始化。
  2. 处理来自客户端的对 service 方法的所有调用。
  3. 从服务中取出 servlet,然后使用 destroy 方法销毁它,最后进行垃圾回收并终止它。

除了生命周期方法之外,此接口还提供了 getServletConfig 方法和 getServletInfo 方法,servlet 可使用前一种方法获得任何启动信息,而后一种方法允许 servlet 返回有关其自身的基本信息,比如作者、版本和版权。

方法总结
image-20210909152224399
destroy
void destroy()

Called by the servlet container to indicate to a servlet that the servlet is being taken out of service. This method is only called once all threads within the servlet’s service method have exited or after a timeout period has passed. After the servlet container calls this method, it will not call the service method again on this servlet.

This method gives the servlet an opportunity to clean up any resources that are being held (for example, memory, file handles, threads) and make sure that any persistent state is synchronized with the servlet’s current state in memory.

​ 由 servlet 容器调用,指示将从服务中取出该 servlet。此方法仅在 servlet 的 service 方法已退出或者在过了超时期之后调用一次。在调用此方法之后,servlet 容器不会再对此 servlet 调用 service 方法。
​ 此方法为 servlet 提供了一个清除持有的所有资源(比如内存、文件句柄和线程)的机会,并确保任何持久状态都与内存中该 servlet 的当前状态保持同步。

getServletConfig
ServletConfig getServletConfig()

Returns a ServletConfig object, which contains initialization and startup parameters for this servlet. The ServletConfigobject returned is the one passed to the init method.

Implementations of this interface are responsible for storing the ServletConfig object so that this method can return it. The GenericServlet class, which implements this interface, already does this.

  • Returns:

    the ServletConfig object that initializes this servlet

    返回 ServletConfig 对象,该对象包含此 servlet 的初始化和启动参数。返回的 ServletConfig 对象是传递给 init 方法的对象。
    此接口的实现负责存储 ServletConfig 对象,以便此方法可以返回该对象。实现此接口的 GenericServlet 类已经这样做了。

  • return 初始化此 servlet 的 ServletConfig 对象

getServletInfo
String getServletInfo()

Returns information about the servlet, such as author, version, and copyright.

The string that this method returns should be plain text and not markup of any kind (such as HTML, XML, etc.).

  • Returns:

    a String containing servlet information

返回有关 servlet 的信息,比如作者、版本和版权。
此方法返回的字符串应该是纯文本,不应该是任何种类的标记(比如 HTML、XML,等等)。

  • return 包含 servlet 信息的 String
init
void init(ServletConfig config)
   throws ServletException

Called by the servlet container to indicate to a servlet that the servlet is being placed into service.

The servlet container calls the init method exactly once after instantiating the servlet. The init method must complete successfully before the servlet can receive any requests.

The servlet container cannot place the servlet into service if the init method

  1. Throws a ServletException
  2. Does not return within a time period defined by the Web server
  • Parameters:

    config - a ServletConfig object containing the servlet’s configuration and initialization parameters

  • Throws:

    ServletException - if an exception has occurred that interferes with the servlet’s normal operation

    由 servlet 容器调用,指示将该 servlet 放入服务。

    servlet 容器仅在实例化 servlet 之后调用 init 方法一次。在 servlet 可以接收任何请求之前,init 方法必须成功完成。

    servlet 容器无法将 servlet 放入服务,如果 init 方法:

  1. 抛出 ServletException
  2. 未在 Web 服务器定义的时间段内返回
  • 参数

    config 包含 servlet 的配置和初始化参数的 ServletConfig 对象

  • 异常

    Throws ServletException: 如果发生妨碍 servlet 正常操作的异常

service
void service(ServletRequest req,
             ServletResponse res)
      throws ServletException,
             IOException

Called by the servlet container to allow the servlet to respond to a request.

This method is only called after the servlet’s init() method has completed successfully.

The status code of the response always should be set for a servlet that throws or sends an error.

Servlets typically run inside multithreaded servlet containers that can handle multiple requests concurrently. Developers must be aware to synchronize access to any shared resources such as files, network connections, and as well as the servlet’s class and instance variables. More information on multithreaded programming in Java is available in the Java tutorial on multi-threaded programming.

  • Parameters:

    req - the ServletRequest object that contains the client’s request

    res - the ServletResponse object that contains the servlet’s response

  • Throws:

    ServletException - if an exception occurs that interferes with the servlet’s normal operation

    IOException - if an input or output exception occurs

由 servlet 容器调用,以允许 servlet 响应某个请求。

此方法仅在 servlet 的 init() 方法成功完成之后调用。

应该为抛出或发送错误的 servlet 设置响应的状态代码。

​ servlet 通常运行在可同时处理多个请求的多线程 servlet 容器中。开发人员必须知道要同步对所有共享资源(比如文件、网络连接以及 servlet 的类和实例变量)的访问。有关 Java 中多线程编程的更多信息,可从 the Java tutorial on multi-threaded programming 中获得。

  • 参数

    req 包含客户端请求的 ServletRequest 对象
    res 包含 servlet 的响应的 ServletResponse 对象

  • 异常

    Throws ServletException: 如果发生妨碍 servlet 正常操作的异常

    Throws java.io.IOException: 如果发生输入或输出异常

ServletRequest

英文简介

Defines an object to provide client request information to a servlet. The servlet container creates a ServletRequest object and passes it as an argument to the servlet’s service method.

A ServletRequest object provides data including parameter name and values, attributes, and an input stream. Interfaces that extend ServletRequest can provide additional protocol-specific data (for example, HTTP data is provided by HttpServletRequest.

中文简介

定义将客户端请求信息提供给某个 servlet 的对象。servlet 容器创建 ServletRequest 对象,并将该对象作为参数传递给该 servlet 的 service 方法。

ServletRequest 对象提供包括参数名称、参数值、属性和输入流的数据。扩展 ServletRequest 的接口可提供其他特定于协议的数据,例如 javax.servlet.http.HttpServletRequest 提供的 HTTP 数据。

方法总结
image-20210909154638110 image-20210909154732557
getContentLength
int getContentLength()

Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known ir is greater than Integer.MAX_VALUE. For HTTP servlets, same as the value of the CGI variable CONTENT_LENGTH.

  • Returns:

    an integer containing the length of the request body or -1 if the length is not known or is greater than Integer.MAX_VALUE.

返回请求正文的长度(以字节为单位),并使输入流可以使用它,如果长度未知,则返回 -1。对于 HTTP servlet,返回的值与 CGI 变量 CONTENT_LENGTH 的值相同。

  • return

    包含请求正文长度的整数,如果长度未知,则返回 -1

getContentType
String getContentType()

Returns the MIME type of the body of the request, or null if the type is not known. For HTTP servlets, same as the value of the CGI variable CONTENT_TYPE.

  • Returns:

    a String containing the name of the MIME type of the request, or null if the type is not known

返回请求正文的 MIME 类型,如果该类型未知,则返回 null。对于 HTTP servlet,返回的值与 CGI 变量 CONTENT_TYPE 的值相同。

  • return

    包含请求的 MIME 类型名称的 String,如果该类型未知,则返回 null

Q 什么是MIME?什么是MIME邮件?

A MIME, 全称为“Multipurpose Internet Mail Extensions”, 比较确切的中文名称为“多用途互联网邮件扩展”。它是当前广泛应用的一种电子邮件技术规范,基本内容定义于RFC 2045-2049。

自然,MIME邮件就是符合MIME规范的电子邮件,或者说根据MIME规范编码而成的电子邮件。

在MIME出台之前,使用RFC 822只能发送基本的ASCII码文本信息,邮件内容如果要包括二进制文件、声音和动画等,实现起来非常困难。MIME提供了一种可以在邮件中附加多种不同编码文件的方法,弥补了原来的信息格式的不足。实际上不仅仅是邮件编码,现在MIME经成为HTTP协议标准的一个部分。

getInputStream
ServletInputStream getInputStream()
                           throws IOException

Retrieves the body of the request as binary data using a ServletInputStream. Either this method or getReader() may be called to read the body, not both.

  • Returns:

    a ServletInputStream object containing the body of the request

  • Throws:

    IllegalStateException - if the getReader() method has already been called for this request

    IOException - if an input or output exception occurred

使用 ServletInputStream 以二进制数据形式获取请求正文。可调用此方法或 getReader 读取正文,而不是两种方法都调用。

  • return

    包含请求正文的 ServletInputStream 对象

  • Throws

    IllegalStateException: 如果已经为此请求调用 getReader 方法

  • Throws

    java.io.IOException: 如果发生输入或输出异常

getParameter
String getParameter(String name)

Returns the value of a request parameter as a String, or null if the parameter does not exist. Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data.

You should only use this method when you are sure the parameter has only one value. If the parameter might have more than one value, use getParameterValues(java.lang.String).

If you use this method with a multivalued parameter, the value returned is equal to the first value in the array returned by getParameterValues.

If the parameter data was sent in the request body, such as occurs with an HTTP POST request, then reading the body directly via getInputStream() or getReader() can interfere with the execution of this method.

  • Parameters:

    name - a String specifying the name of the parameter

  • Returns:

    a String representing the single value of the parameter

以 String 形式返回请求参数的值,如果该参数不存在,则返回 null。请求参数是与请求一起发送的额外信息。对于 HTTP servlet,参数包含在查询字符串或发送的表单数据中。

只有在确定参数只有一个值时,才应该使用此方法。如果参数可能拥有一个以上的值,则使用 #getParameterValues。

如果将此方法用于一个有多个值的参数,则返回的值等于 getParameterValues 返回的数组中的第一个值。

如果参数数据是在请求正文中发送的,比如发生在 HTTP POST 请求中,则通过 #getInputStream 或 #getReader 直接读取正文可能妨碍此方法的执行。

  • 参数

    name 指定参数名称的 String

  • 返回值

    return 表示单个参数值的 String

getParameterValues
String[] getParameterValues(String name)

Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist.

If the parameter has a single value, the array has a length of 1.

  • Parameters:

    name - a String containing the name of the parameter whose value is requested

  • Returns:

    an array of String objects containing the parameter’s values

返回包含给定请求参数拥有的所有值的 String 对象数组,如果该参数不存在,则返回 null。

如果该参数只有一个值,则数组的长度为 1。

  • 参数

    name 包含请求其值的参数的名称的 String

  • 返回值

    return 包含参数值的 String 对象数组

getReader
BufferedReader getReader()
                  throws IOException

Retrieves the body of the request as character data using a BufferedReader. The reader translates the character data according to the character encoding used on the body. Either this method or getInputStream() may be called to read the body, not both.

  • Returns:

    a BufferedReader containing the body of the request

  • Throws:

    UnsupportedEncodingException - if the character set encoding used is not supported and the text cannot be decoded

    IllegalStateException - if getInputStream() method has been called on this request

    IOException - if an input or output exception occurred

使用 BufferedReader 以字符数据形式获取请求正文。读取器根据正文上使用的字符编码转换字符数据。可调用此方法或 #getInputStream 读取正文,而不是两种方法都调用。

  • 返回值

    return 包含请求正文的 BufferedReader

  • 异常

    Throws UnsupportedEncodingException: 如果使用的字符集编码不受支持,并且无法对文本进行解码
    Throws IllegalStateException: 如果已对此请求调用 #getInputStream 方法
    Throws java.io.IOException: 如果发生输入或输出异常

getLocalPort
String getLocalAddr()

Returns the Internet Protocol (IP) address of the interface on which the request was received.

  • Returns:

    a String containing the IP address on which the request was received.

返回接收请求的接口的 Internet Protocol (IP) 端口号。

  • 返回值

    return 指定端口号的整数

ServletResponse

英文简介

Defines an object to assist a servlet in sending a response to the client. The servlet container creates a ServletResponse object and passes it as an argument to the servlet’s service method.

To send binary data in a MIME body response, use the ServletOutputStream returned by getOutputStream(). To send character data, use the PrintWriter object returned by getWriter(). To mix binary and text data, for example, to create a multipart response, use a ServletOutputStream and manage the character sections manually.

The charset for the MIME body response can be specified explicitly using any of the following techniques: per request, per web-app (using ServletContext.setRequestCharacterEncoding(java.lang.String), deployment descriptor), and per container (for all web applications deployed in that container, using vendor specific configuration). If multiple of the preceding techniques have been employed, the priority is the order listed. For per request, the charset for the response can be specified explicitly using the setCharacterEncoding(java.lang.String) and setContentType(java.lang.String) methods, or implicitly using the setLocale(java.util.Locale) method. Explicit specifications take precedence over implicit specifications. If no charset is explicitly specified, ISO-8859-1 will be used. The setCharacterEncoding, setContentType, or setLocale method must be called before getWriter and before committing the response for the character encoding to be used.

See the Internet RFCs such as RFC 2045 for more information on MIME. Protocols such as SMTP and HTTP define profiles of MIME, and those standards are still evolving.

中文简介

定义辅助 servlet 将响应发送到客户端的对象。servlet 容器创建 ServletResponse 对象,并将它作为参数传递给 servlet 的 service 方法。

要发送 MIME 正文响应中的二进制数据,请使用 #getOutputStream 返回的 ServletOutputStream。要发送字符数据,请使用 #getWriter 返回的 PrintWriter 对象。要混合二进制数据和文本数据,例如要创建 multipart 响应,请使用 ServletOutputStream 并手动管理字符部分。

可使用 #setCharacterEncoding#setContentType 显式指定 MIME 正文响应的 charset,或使用 #setLocale 方法隐式指定它。显式指定优先于隐式指定。如果未指定 charset,则将使用 ISO-8859-1。setCharacterEncodingsetContentTypesetLocale 方法必须在调用 getWriter 之前,并且必须在提交采用要使用的字符编码的响应之前调用。

有关 MIME 的更多信息,请参见 Internet RFC,比如 RFC 2045。诸如 SMTP 和 HTTP 之类的协议定义了 MIME 的配置文件,并且那些标准仍在不断发展。

方法总结
image-20210909161617690
getContentType
String getContentType()

Returns the content type used for the MIME body sent in this response. The content type proper must have been specified using setContentType(java.lang.String) before the response is committed. If no content type has been specified, this method returns null. If a content type has been specified, and a character encoding has been explicitly or implicitly specified as described in getCharacterEncoding() or getWriter() has been called, the charset parameter is included in the string returned. If no character encoding has been specified, the charset parameter is omitted.

  • Returns:

    a String specifying the content type, for example, text/html; charset=UTF-8, or null

返回用于此响应中发送的 MIME 正文的内容类型。必须在提交响应之前已使用 #setContentType 指定适当的内容类型。如果未指定内容类型,则此方法返回 null。如果已指定内容类型,并且已经如 #getCharacterEncoding 中所述显式或隐式指定了字符编码或者已调用 #getWriter,则返回的字符串中将包含 charset 参数。如果未指定字符编码,则省略 charset 参数。

  • 返回值

    return 指定内容类型的 String,例如 text/html; charset=UTF-8,或者返回 null

getOutputStream
ServletOutputStream getOutputStream()
                             throws IOException

Returns a ServletOutputStream suitable for writing binary data in the response. The servlet container does not encode the binary data.

Calling flush() on the ServletOutputStream commits the response. Either this method or getWriter() may be called to write the body, not both, except when reset() has been called.

  • Returns:

    a ServletOutputStream for writing binary data

  • Throws:

    IllegalStateException - if the getWriter method has been called on this response

    IOException - if an input or output exception occurred

返回适用于在响应中编写二进制数据的 ServletOutputStream。servlet 容器不会编码二进制数据。

对 ServletOutputStream 调用 flush() 将提交响应。 可调用此方法或 #getWriter 编写正文,而不是两种方法都调用。

  • 返回值

    return 用于编写二进制数据的 ServletOutputStream

  • 异常

    Throws IllegalStateException: 如果已对此响应调用 getWriter 方法
    Throws java.io.IOException: 如果发生输入或输出异常

getWriter
PrintWriter getWriter()
               throws IOException

Returns a PrintWriter object that can send character text to the client. The PrintWriter uses the character encoding returned by getCharacterEncoding(). If the response’s character encoding has not been specified as described in getCharacterEncoding (i.e., the method just returns the default value ISO-8859-1), getWriter updates it to ISO-8859-1.

Calling flush() on the PrintWriter commits the response.

Either this method or getOutputStream() may be called to write the body, not both, except when reset() has been called.

  • Returns:

    a PrintWriter object that can return character data to the client

  • Throws:

    UnsupportedEncodingException - if the character encoding returned by getCharacterEncoding cannot be used

    IllegalStateException - if the getOutputStream method has already been called for this response object

    IOException - if an input or output exception occurred

返回可将字符文本发送到客户端的 PrintWriter 对象。PrintWriter 使用 #getCharacterEncoding 返回的字符编码。如果未如 getCharacterEncoding 中所述指定响应的字符编码(即该方法只返回默认值 ISO-8859-1),则 getWriter 会将字符编码更新到 ISO-8859-1。

对 PrintWriter 调用 flush() 将提交响应。

可调用此方法或 #getOutputStream 编写正文,而不是两种方法都调用。

  • 返回值

    return 可将字符数据返回到客户端的 PrintWriter 对象。

  • 异常

    Throws UnsupportedEncodingException: 如果无法使用 getCharacterEncoding 返回的字符编码
    Throws IllegalStateException: 如果已对此响应对象调用 getOutputStream 方法
    Throws java.io.IOException: 如果发生输入或输出异常

setContentLength
void setContentLength(int len)

Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length header.

  • Parameters:

    len - an integer specifying the length of the content being returned to the client; sets the Content-Length header

设置 HTTP servlet 中响应的内容正文的长度,此方法设置 HTTP Content-Length 头。

  • 参数

    len 指定将返回到客户端的内容长度的整数;设置 Content-Length 头

setContentType
void setContentType(String type)

Sets the content type of the response being sent to the client, if the response has not been committed yet. The given content type may include a character encoding specification, for example, text/html;charset=UTF-8. The response’s character encoding is only set from the given content type if this method is called before getWriter is called.

This method may be called repeatedly to change content type and character encoding. This method has no effect if called after the response has been committed. It does not set the response’s character encoding if it is called after getWriter has been called or after the response has been committed.

Containers must communicate the content type and the character encoding used for the servlet response’s writer to the client if the protocol provides a way for doing so. In the case of HTTP, the Content-Type header is used.

  • Parameters:

    type - a String specifying the MIME type of the content

设置将发送到客户端的响应的内容类型,如果该响应尚未提交。给定内容类型可能包含字符编码规范,例如 text/html;charset=UTF-8。如果在调用 getWriter 之前调用此方法,则只根据给定内容类型设置响应的字符编码。

可重复调用此方法来更改内容类型和字符编码。如果在已提交响应之后调用此方法,则此方法没有任何效果。如果在已调用 getWriter 之后或者在已提交响应之后调用此方法,则该方法不会设置响应的字符编码。

容器必须让客户端了解用于 servlet 响应的 writer 的内容类型和字符编码,如果协议提供了实现上述操作的方法。在使用 HTTP 的情况下,使用 Content-Type 头。

  • 参数

    type 指定内容的 MIME 类型的 String

reset
void reset()

Clears any data that exists in the buffer as well as the status code, headers. The state of calling getWriter() or getOutputStream() is also cleared. It is legal, for instance, to call getWriter(), reset() and then getOutputStream(). If getWriter() or getOutputStream() have been called before this method, then the corrresponding returned Writer or OutputStream will be staled and the behavior of using the stale object is undefined. If the response has been committed, this method throws an IllegalStateException.

  • Throws:

    IllegalStateException - if the response has already been committed

清除缓冲区中存在的所有数据以及状态代码和头。如果已提交响应,则此方法将抛出 IllegalStateException。

  • 异常

    Throws IllegalStateException: 如果已提交响应

HttpServletRequest

英文简介
public interface HttpServletRequest
extends ServletRequest

Extends the ServletRequest interface to provide request information for HTTP servlets.

The servlet container creates an HttpServletRequest object and passes it as an argument to the servlet’s service methods (doGet, doPost, etc).

中文简介

扩展 javax.servlet.ServletRequest 接口,为 HTTP servlet 提供请求信息。

servlet 容器创建 HttpServletRequest 对象,并将该对象作为参数传递给 servlet 的 service 方法(doGetdoPost,等等)。

方法总结
image-20210910153625499 image-20210910153726084
getContextPath
String getContextPath()

Returns the portion of the request URI that indicates the context of the request. The context path always comes first in a request URI. The path starts with a “/” character but does not end with a “/” character. For servlets in the default (root) context, this method returns “”. The container does not decode this string.

It is possible that a servlet container may match a context by more than one context path. In such cases this method will return the actual context path used by the request and it may differ from the path returned by theServletContext.getContextPath() method. The context path returned byServletContext.getContextPath() should be considered as the prime or preferred context path of the application.

  • Returns:

    a String specifying the portion of the request URI that indicates the context of the request

返回请求 URI 指示请求上下文的那一部分。请求 URI 中首先出现的总是上下文路径。路径以 “/” 字符开头但不以 “/” 字符结束。对于默认(根)上下文中的 servlet,此方法返回 “”。容器不会解码此字符串。

servlet 容器可能通过多个上下文路径匹配一个上下文。在这种情况下,此方法将返回该请求使用的实际上下文路径,该路径可能不同于 getContextPath() 方法返回的路径。getContextPath() 返回的上下文路径应该被认为是应用程序的主要或首选上下文路径。

​ return 指定请求 URI 指示请求上下文的那一部分的 String

getDateHeader
long getDateHeader(String name)

Returns the value of the specified request header as a long value that represents a Date object. Use this method with headers that contain dates, such as If-Modified-Since.

The date is returned as the number of milliseconds since January 1, 1970 GMT. The header name is case insensitive.

If the request did not have a header of the specified name, this method returns -1. If the header can’t be converted to a date, the method throws an IllegalArgumentException.

  • Parameters:

    name - a String specifying the name of the header

  • Returns:

    a long value representing the date specified in the header expressed as the number of milliseconds since January 1, 1970 GMT, or -1 if the named header was not included with the request

  • Throws:

    IllegalArgumentException - If the header value can’t be converted to a date

以表示 Date 对象的 long 值的形式返回指定请求头的值。与包含日期的头(比如 If-Modified-Since)一起使用此方法。

返回的日期是自格林威治标准时间 1970 年 1 月 1 日起经过的毫秒数。头名称是不区分大小写的。

如果该请求没有指定名称的头,则此方法返回 -1。如果无法将头转换为日期,则该方法将抛出 IllegalArgumentException。

  • 参数

    name 指定头名称的 String

  • 返回值

    return 表示头中指定的日期的 long 值,该日期被表示为自格林威治标准时间 1970 年 1 月 1 日起经过的毫秒数,如果请求中不包含指定的头,则返回 -1

  • 异常

    Throws IllegalArgumentException: 如果无法将头值转换为日期

getHeader
String getHeader(String name)

Returns the value of the specified request header as a String. If the request did not include a header of the specified name, this method returns null. If there are multiple headers with the same name, this method returns the first head in the request. The header name is case insensitive. You can use this method with any request header.

  • Parameters:

    name - a String specifying the header name

  • Returns:

    a String containing the value of the requested header, or null if the request does not have a header of that name

以 String 的形式返回指定请求头的值。如果该请求不包含指定名称的头,则此方法返回 null。如果有多个具有相同名称的头,则此方法返回请求中的第一个头。头名称是不区分大小写的。可以将此方法与任何请求头一起使用。

  • 参数

    name 指定头名称的 String

  • 返回

    return 包含请求头的值的 String,如果该请求没有该名称的头,则返回 null

getHeaders
Enumeration<String> getHeaders(String name)

Returns all the values of the specified request header as an Enumeration of String objects.

Some headers, such as Accept-Language can be sent by clients as several headers each with a different value rather than sending the header as a comma separated list.

If the request did not include any headers of the specified name, this method returns an empty Enumeration. The header name is case insensitive. You can use this method with any request header.

  • Parameters:

    name - a String specifying the header name

  • Returns:

    an Enumeration containing the values of the requested header. If the request does not have any headers of that name return an empty enumeration. If the container does not allow access to header information, return null

以 String 对象的 Enumeration 的形式返回指定请求头的所有值。

一些头(比如 Accept-Language)能够以具有不同值的几个头的形式由客户端发送,而不采用以逗号分隔的列表的形式发送该头。

如果该请求不包含任何指定名称的头,则此方法返回一个空的 Enumeration。头名称是不区分大小写的。可以将此方法与任何请求头一起使用。

  • 参数

    name 指定头名称的 String

  • 返回值

    return 包含请求头的值的 Enumeration。如果该请求不包含任何具有该名称的头,则返回一个空枚举。如果容器不允许访问头信息,则返回 null

getHeaderNames
Enumeration<String> getHeaderNames()

Returns an enumeration of all the header names this request contains. If the request has no headers, this method returns an empty enumeration.

Some servlet containers do not allow servlets to access headers using this method, in which case this method returns null

  • Returns:

    an enumeration of all the header names sent with this request; if the request has no headers, an empty enumeration; if the servlet container does not allow servlets to use this method, null

返回此请求包含的所有头名称的枚举。如果该请求没有头,则此方法返回一个空枚举。

一些 servlet 容器不允许 servlet 使用此方法访问头,在这种情况下,此方法返回 null。

  • 返回值

    return 随此请求一起发送的所有头名称的枚举;如果该请求没有头,则返回一个空枚举;如果 servlet 容器不允许 servlet 使用此方法,则返回 null

getMethod
String getMethod()

Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT. Same as the value of the CGI variable REQUEST_METHOD.

  • Returns:

    a String specifying the name of the method with which this request was made

返回用于发出此请求的 HTTP 方法的名称,例如 GET、POST 或 PUT。返回的值与 CGI 变量 REQUEST_METHOD 的值相同。

  • 返回值

return 指定用于发出此请求的方法名称的 String

getRequestURI
String getRequestURI()

Returns the part of this request’s URL from the protocol name up to the query string in the first line of the HTTP request. The web container does not decode this String. For example:

First line of HTTP requestReturned Value
POST /some/path.html HTTP/1.1/some/path.html
GET http://foo.bar/a.html HTTP/1.0/a.html
HEAD /xyz?a=b HTTP/1.1/xyz

To reconstruct an URL with a scheme and host, useHttpUtils.getRequestURL(javax.servlet.http.HttpServletRequest).

  • Returns:

    a String containing the part of the URL from the protocol name up to the query string

返回此请求的 URL 的一部分,从协议名称一直到 HTTP 请求的第一行中的查询字符串。Web 容器不会解码此 String。例如:
HTTP 请求的第一行 返回的值
POST /some/path.html HTTP/1.1 /some/path.html
GET http://foo.bar/a.html HTTP/1.0 /a.html
HEAD /xyz?a=b HTTP/1.1 /xyz

要使用某个方案和主机重新构造 URL,可使用 HttpUtils#getRequestURL。

  • 返回值

    return 包含 URL 从协议名称一直到查询字符串的那一部分的 String

getRequestURL
StringBuffer getRequestURL()

Reconstructs the URL the client used to make the request. The returned URL contains a protocol, server name, port number, and server path, but it does not include query string parameters.

If this request has been forwarded usingRequestDispatcher.forward(javax.servlet.ServletRequest, javax.servlet.ServletResponse), the server path in the reconstructed URL must reflect the path used to obtain the RequestDispatcher, and not the server path specified by the client.

Because this method returns a StringBuffer, not a string, you can modify the URL easily, for example, to append query parameters.

This method is useful for creating redirect messages and for reporting errors.

  • Returns:

    a StringBuffer object containing the reconstructed URL

重新构造客户端用于发出请求的 URL。返回的 URL 包含一个协议、服务器名称、端口号、服务器路径,但是不包含查询字符串参数。
如果已经使用 javax.servlet.RequestDispatcher#forward 转发了此请求,则重新构造的 URL 中的服务器路径必须反映用于获取 RequestDispatcher 的路径,而不是客户端指定的服务器路径。

因为此方法返回 StringBuffer 而不是字符串,所以可以轻松地修改 URL,例如,可以追加查询参数。

此方法对于创建重定向消息和报告错误很有用。

  • 返回

    return 包含重新构造的 URL 的 StringBuffer 对象

HttpServletResponse

英文简介
public interface HttpServletResponse
extends ServletResponse

Extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. For example, it has methods to access HTTP headers and cookies.

The servlet container creates an HttpServletResponse object and passes it as an argument to the servlet’s service methods (doGet, doPost, etc).

中文简介

扩展 ServletResponse 接口以提供特定于 HTTP 的发送响应功能。例如,该接口拥有访问 HTTP 头和 cookie 的方法。

servlet 容器创建 HttpServletResponse 对象,并将该对象作为参数传递给 servlet 的 service 方法(doGetdoPost,等等)。

方法总结
getHeader
String getHeader(String name)

Gets the value of the response header with the given name.

If a response header with the given name exists and contains multiple values, the value that was added first will be returned.

This method considers only response headers set or added via setHeader(java.lang.String, java.lang.String), addHeader(java.lang.String, java.lang.String), setDateHeader(java.lang.String, long), addDateHeader(java.lang.String, long), setIntHeader(java.lang.String, int), or addIntHeader(java.lang.String, int), respectively.

  • Parameters:

    name - the name of the response header whose value to return

  • Returns:

    the value of the response header with the given name, or null if no header with the given name has been set on this response

getHeaderNames
Collection<String> getHeaderNames()

Gets the names of the headers of this response.

This method considers only response headers set or added via setHeader(java.lang.String, java.lang.String), addHeader(java.lang.String, java.lang.String), setDateHeader(java.lang.String, long), addDateHeader(java.lang.String, long), setIntHeader(java.lang.String, int), or addIntHeader(java.lang.String, int), respectively.

Any changes to the returned Collection must not affect this HttpServletResponse.

  • Returns:

    a (possibly empty) Collection of the names of the headers of this response

getHeaders
Collection<String> getHeaders(String name)

Gets the values of the response header with the given name.

This method considers only response headers set or added via setHeader(java.lang.String, java.lang.String), addHeader(java.lang.String, java.lang.String), setDateHeader(java.lang.String, long), addDateHeader(java.lang.String, long), setIntHeader(java.lang.String, int), or addIntHeader(java.lang.String, int), respectively.

Any changes to the returned Collection must not affect this HttpServletResponse.

  • Parameters:

    name - the name of the response header whose values to return

  • Returns:

    a (possibly empty) Collection of the values of the response header with the given name

  • Since:

    Servlet 3.0

setHeader
void setHeader(String name,
               String value)

Sets a response header with the given name and value. If the header had already been set, the new value overwrites the previous one. The containsHeadermethod can be used to test for the presence of a header before setting its value.

  • Parameters:

    name - the name of the header

    value - the header value If it contains octet string, it should be encoded according to RFC 2047

用给定名称和值设置响应头。如果已经设置了头,则新值将重写以前的值。containsHeader 方法可用于测试在设置其值之前头是否存在。

  • 参数

    name 头的名称

  • 返回值

    value 头值,如果该值包含八位字节字符串,则应该根据 RFC 2047 (http://www.ietf.org/rfc/rfc2047.txt) 对其进行编码

ServletConfig

英文简介

A servlet configuration object used by a servlet container to pass information to a servlet during initialization.

中文简介

servlet 容器使用的 servlet 配置对象,该对象在初始化期间将信息传递给 servlet。

方法总结
image-20210916155122066
getInitParameter
String getInitParameter(String name)

Gets the value of the initialization parameter with the given name.

  • Parameters:

    name - the name of the initialization parameter whose value to get

  • Returns:

    a String containing the value of the initialization parameter, or null if the initialization parameter does not exist

返回包含指定初始化参数的值的 String,如果参数不存在,则返回 null。

  • 参数

    name 指定初始化参数名称的 String

  • 返回值

    return 包含初始化参数值的 String

getInitParameterNames
Enumeration<String> getInitParameterNames()

Returns the names of the servlet’s initialization parameters as an Enumeration of String objects, or an empty Enumeration if the servlet has no initialization parameters.

  • Returns:

    an Enumeration of String objects containing the names of the servlet’s initialization parameters

以 String 对象的 Enumeration 的形式返回 servlet 的初始化参数的名称,如果 servlet 没有初始化参数,则返回一个空的 Enumeration。

  • 返回值

    return 包含 servlet 初始化参数名称的 String 对象的 Enumeration

getServletContext
ServletContext getServletContext()

Returns a reference to the ServletContext in which the caller is executing.

  • Returns:

    a ServletContext object, used by the caller to interact with its servlet container

返回对调用者在其中执行操作的 ServletContext 的引用。

  • 返回值

return 一个 ServletContext 对象,调用者用于与其 servlet 容器交互

ServletContext

英文简介
public interface ServletContext

Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.

There is one context per “web application” per Java Virtual Machine. (A “web application” is a collection of servlets and content installed under a specific subset of the server’s URL namespace such as /catalog and possibly installed via a .war file.)

In the case of a web application marked “distributed” in its deployment descriptor, there will be one context instance for each virtual machine. In this situation, the context cannot be used as a location to share global information (because the information won’t be truly global). Use an external resource like a database instead.

The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized.

中文简介

定义一组方法,servlet 使用这些方法与其 servlet 容器进行通信,例如,获取文件的 MIME 类型、分发请求或写入日志文件。

每个 Java 虚拟机的每个“Web 应用程序”都有一个上下文。(“Web 应用程序”是 servlet 和内容的 Collection,这些 servlet 和内容安装在服务器的 URL 名称空间(比如 /catalog)的特定子集下,并且可能通过 .war 文件安装。)

如果 Web 应用程序在其部署描述符中标记为 “distributed”,那么每个虚拟机都将有一个上下文实例。在这种情况下,不能将上下文用作共享全局信息的位置(因为该信息不会是真正全局共享的)。请使用外部资源(如数据库)替代。

ServletContext 对象包含在 ServletConfig 对象中,ServletConfig 对象在初始化 servlet 时由 Web 服务器提供给 servlet。

方法总结
image-20210916155344918 image-20210916155410088 image-20210916155433375
方法总结
getAttribute
Object getAttribute(String name)

Returns the servlet container attribute with the given name, or null if there is no attribute by that name.

An attribute allows a servlet container to give the servlet additional information not already provided by this interface. See your server documentation for information about its attributes. A list of supported attributes can be retrieved using getAttributeNames.

The attribute is returned as a java.lang.Object or some subclass.

Attribute names should follow the same convention as package names. The Java Servlet API specification reserves names matching java.*, javax.*, and sun.*.

  • Parameters:

    name - a String specifying the name of the attribute

  • Returns:

    an Object containing the value of the attribute, or null if no attribute exists matching the given name.

  • Throws:

    NullPointerException - if the argument name is null

    返回具有给定名称的 servlet 容器属性,如果不具有该名称的属性,则返回 null。属性允许 servlet 容器将此接口还没有提供的额外信息提供给 servlet。有关其属性的信息,请参见服务器文档。可使用 getAttributeNames 获取支持的属性的列表。

    属性是以 java.lang.Object 或某个子类的形式返回的。属性名称应该与包名称遵守相同的约定。Java Servlet API 规范保留匹配 java.、javax. 和 sun.* 的名称。

    • 参数

      name 指定属性名称的 String

    • 返回值

      return 包含属性值的 Object,如果不存在匹配给定名称的属性,则返回 null

getAttributeNames
Enumeration<String> getAttributeNames()

Returns an Enumeration containing the attribute names available within this ServletContext.

Use the getAttribute(java.lang.String) method with an attribute name to get the value of an attribute.

  • Returns:

    an Enumeration of attribute names

返回包含此 servlet 上下文中可用属性的名称的 Enumeration。使用带有一个属性名称的 #getAttribute 方法获取属性值。

return 属性名称的 Enumeration

setAttribute
void setAttribute(String name,
                  Object object)

Binds an object to a given attribute name in this ServletContext. If the name specified is already used for an attribute, this method will replace the attribute with the new to the new attribute.

If listeners are configured on the ServletContext the container notifies them accordingly.

If a null value is passed, the effect is the same as calling removeAttribute().

Attribute names should follow the same convention as package names. The Java Servlet API specification reserves names matching java.*, javax.*, andsun.*.

  • Parameters:

    name - a String specifying the name of the attribute

    object - an Object representing the attribute to be bound

  • Throws:

    NullPointerException - if the name parameter is null

将对象绑定到此 servlet 上下文中的给定属性名称。如果已将指定名称用于某个属性,则此方法将使用新属性替换具有该名称的属性。

如果在 ServletContext 上配置了侦听器,则容器将相应地通知它们。

如果传递了 null 值,则效果将与调用 removeAttribute() 相同。

属性名称应该与包名称遵守相同的约定。Java Servlet API 规范保留匹配 java.、javax. 和 sun.* 的名称。

  • 参数

    name 指定属性名称的 String

    object 表示要绑定的属性的 Object

removeAttribute
void removeAttribute(String name)

Removes the attribute with the given name from this ServletContext. After removal, subsequent calls to getAttribute(java.lang.String) to retrieve the attribute’s value will return null.

If listeners are configured on the ServletContext the container notifies them accordingly.

  • Parameters:

    name - a String specifying the name of the attribute to be removed

从 servlet 上下文中移除具有给定名称的属性。完成移除操作后,为获取属性值而对 #getAttribute 进行的后续调用将返回 null。

如果在 ServletContext 上配置了侦听器,则容器将相应地通知它们。

  • 参数

    name 指定要移除的属性的名称的 String

getContext
ServletContext getContext(String uripath)

Returns a ServletContext object that corresponds to a specified URL on the server.

This method allows servlets to gain access to the context for various parts of the server, and as needed obtain RequestDispatcher objects from the context. The given path must be begin with /, is interpreted relative to the server’s document root and is matched against the context roots of other web applications hosted on this container.

In a security conscious environment, the servlet container may return null for a given URL.

  • Parameters:

    uripath - a String specifying the context path of another web application in the container.

  • Returns:

    the ServletContext object that corresponds to the named URL, or null if either none exists or the container wishes to restrict this access.

返回与服务器上的指定 URL 相对应的 ServletContext 对象。

此方法允许 servlet 获得对服务器各个部分的上下文的访问,并根据需要从上下文中获得 RequestDispatcher 对象。给定路径必须以 “/” 开头,相对于服务器的文档根进行解释,并与宿主在此容器上的其他 Web 应用程序的上下文根匹配。

在安全意识较强的环境中,servlet 容器可能对给定 URL 返回 null。

  • 参数

    uripath 指定容器中另一个 Web 应用程序的上下文路径的 String。

  • 返回值

    return 与指定 URL 相对应的 ServletContext 对象;如果该对象不存在,或者容器希望限制 此访问,则返回 null。

getServletContextName
String getServletContextName()

Returns the name of this web application corresponding to this ServletContext as specified in the deployment descriptor for this web application by the display-name element.

  • Returns:

    The name of the web application or null if no name has been declared in the deployment descriptor.

返回与此 ServletContext 相对应的 Web 应用程序的名称,该名称是通过 display-name 元素在部署描述符中为此 Web 应用程序指定的。

  • 返回值

return Web 应用程序的名称,如果尚未在部署描述符中声明该名称,则返回 null。

HttpSession

英文简介

Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.

The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user. A session usually corresponds to one user, who may visit a site many times. The server can maintain a session in many ways such as using cookies or rewriting URLs.

This interface allows servlets to

  • View and manipulate information about a session, such as the session identifier, creation time, and last accessed time
  • Bind objects to sessions, allowing user information to persist across multiple user connections

When an application stores an object in or removes an object from a session, the session checks whether the object implements HttpSessionBindingListener. If it does, the servlet notifies the object that it has been bound to or unbound from the session. Notifications are sent after the binding methods complete. For session that are invalidated or expire, notifications are sent after the session has been invalidated or expired.

When container migrates a session between VMs in a distributed container setting, all session attributes implementing the HttpSessionActivationListenerinterface are notified.

A servlet should be able to handle cases in which the client does not choose to join a session, such as when cookies are intentionally turned off. Until the client joins the session, isNew returns true. If the client chooses not to join the session, getSession will return a different session on each request, and isNew will always returntrue.

Session information is scoped only to the current web application (ServletContext), so information stored in one context will not be directly visible in another.

中文简介

提供一种方式,跨多个页面请求或对 Web 站点的多次访问标识用户并存储有关该用户的信息。

servlet 容器使用此接口创建 HTTP 客户端和 HTTP 服务器之间的会话。会话将保留指定的时间段,跨多个连接或来自用户的页面请求。一个会话通常对应于一个用户,该用户可能多次访问一个站点。服务器能够以多种方式维护会话,比如使用 cookie 或重写 URL。

此接口允许 servlet

  • 查看和操作有关某个会话的信息,比如会话标识符、创建时间和最后一次访问时间
  • 将对象绑定到会话,允许跨多个用户连接保留用户信息

当应用程序将对象存储到会话中或从会话中移除对象时,该会话将检查对象是否实现了 HttpSessionBindingListener。如果实现了,则 servlet 将通知该对象它已经被绑定到会话,或者已从会话中取消对它的绑定。通知是在绑定方法完成后发送的。对于无效或过期的会话,通知是在会话已经无效或过期之后发送的。

当容器使用分布式容器设置在 VM 之间迁移会话时,所有实现 HttpSessionActivationListener 接口的会话属性都会得到通知。

servlet 应该能够处理客户端选择不加入会话的情况,比如故意关闭 cookie 时。在客户端加入会话前,isNew 一直返回 true。如果客户端选择不加入会话,则 getSession 将对每个请求返回一个不同的会话,并且 isNew 将总是返回 true

会话信息的范围仅限于当前 Web 应用程序 (ServletContext),因此存储在一个上下文中的信息在另一个上下文中不是直接可见的。

方法总结
image-20210916153528882
getAttribute
Object getAttribute(String name)

Returns the object bound with the specified name in this session, or null if no object is bound under the name.

  • Parameters:

    name - a string specifying the name of the object

  • Returns:

    the object with the specified name

  • Throws:

    IllegalStateException - if this method is called on an invalidated session

返回与此会话中的指定名称绑定在一起的对象,如果没有对象绑定在该名称下,则返回 null。

  • 参数:

name 指定对象名称的字符串

  • 返回值:

return 具有指定名称的对象

  • 异常

Throws IllegalStateException: 如果对无效的会话调用此方法

getAttributeNames
Enumeration<String> getAttributeNames()

Returns an Enumeration of String objects containing the names of all the objects bound to this session.

  • Returns:

    an Enumeration of String objects specifying the names of all the objects bound to this session

  • Throws:

    IllegalStateException - if this method is called on an invalidated session

返回包含绑定到此会话的所有对象的名称的 String 对象的 Enumeration。

  • 返回值

    return 指定绑定到此会话的所有对象的名称的

  • 参数

    String 对象的 Enumeration。

  • 异常

    Throws IllegalStateException: 如果对无效的会话调用此方法

getServletContext
ServletContext getServletContext()

Returns the ServletContext to which this session belongs.

  • Returns:

    The ServletContext object for the web application

返回此会话所属的 ServletContext。

  • 返回值

    return Web 应用程序的 ServletContext 对象

setAttribute
void setAttribute(String name,
                  Object value)

Binds an object to this session, using the name specified. If an object of the same name is already bound to the session, the object is replaced.

After this method executes, and if the new object implements HttpSessionBindingListener, the container calls HttpSessionBindingListener.valueBound. The container then notifies any HttpSessionAttributeListeners in the web application.

If an object was already bound to this session of this name that implements HttpSessionBindingListener, its HttpSessionBindingListener.valueUnbound method is called.

If the value passed in is null, this has the same effect as calling removeAttribute().

  • Parameters:

    name - the name to which the object is bound; cannot be null

    value - the object to be bound

  • Throws:

    IllegalStateException - if this method is called on an invalidated session

使用指定名称将对象绑定到此会话。如果具有同样名称的对象已经绑定到该会话,则替换该对象。

在执行此方法后,如果新对象实现了 HttpSessionBindingListener,则容器将调用 HttpSessionBindingListener.valueBound。然后,容器通知 Web 应用程序中的任何 HttpSessionAttributeListener。

如果某个对象已经使用此名称绑定到了此会话且该对象实现了 HttpSessionBindingListener,则调用它的 HttpSessionBindingListener.valueUnbound 方法。

如果传入的值为 null,则调用此方法将与调用 removeAttribute() 产生的效果相同。

  • 参数

    name 对象绑定到的名称;不能为 null

    value 要绑定的对象

  • 异常

    Throws IllegalStateException: 如果对无效的会话调用此方法

removeAttribute
void removeAttribute(String name)

Removes the object bound with the specified name from this session. If the session does not have an object bound with the specified name, this method does nothing.

After this method executes, and if the object implements HttpSessionBindingListener, the container calls HttpSessionBindingListener.valueUnbound. The container then notifies any HttpSessionAttributeListeners in the web application.

  • Parameters:

    name - the name of the object to remove from this session

  • Throws:

    IllegalStateException - if this method is called on an invalidated session

从此会话中移除与指定名称绑定在一起的对象。如果会话没有与指定名称绑定在一起的对象,则此方法不执行任何操作。

在执行此方法后,如果对象实现了 HttpSessionBindingListener,则容器将调用 HttpSessionBindingListener.valueUnbound。然后,容器通知 Web 应用程序中的任何 HttpSessionAttributeListener。

  • 参数

    name 要从此会话中移除的对象的名称

  • 异常

    Throws IllegalStateException: 如果对无效的会话调用此方法

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐