English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

响应服务器 JSP

L'oggetto di risposta Response trasmette principalmente i risultati elaborati dal container JSP al client. Puoi impostare lo stato HTTP e inviare dati al client tramite la variabile response, come Cookie, intestazioni HTTP ecc.

Una risposta tipica assomiglia a quella che segue:

HTTP/1.1 200 OK
Content-Type: text/html
Header2:...
...
HeaderN:...
  (riga vuota)
!doctype...
<html>
<head>...</head>
<body>
...
</body>
</html>

La riga di stato contiene informazioni sulla versione HTTP, come HTTP/1.1, un codice di stato come 200 e un messaggio molto breve corrispondente al codice di stato, come OK.

La tabella seguente riassume le parti più utili degli intestazioni di risposta HTTP 1.1, che vedrete spesso nella programmazione di rete:

Intestazione di risposta描述
Permetti Specifica i metodi di richiesta supportati dal server (GET, POST ecc.)
Controllo del cache Specifica le condizioni in cui il documento di risposta può essere memorizzato in modo sicuro. Di solito ha il valore PubblicoCommaPrivato ONo-cache Ecc. Public significa che il documento è memorizzabile nel cache, Private significa che il documento è per un singolo utente e può essere utilizzato solo nel cache privato. No-cache significa che il documento non viene memorizzato nel cache.
Connessione Comanda al browser se utilizzare una connessione HTTP persistente.ChiudiValore Comanda al browser di non utilizzare una connessione HTTP persistente, mentre keep-alive significa utilizzare una connessione persistente.
Posizione del contenuto Fa sì che il browser chieda all'utente di salvare la risposta con un nome specificato sul disco
Codifica del contenuto Specifica le regole di codifica della pagina durante la trasmissione
Lingua del contenuto Esprime la lingua utilizzata nel documento, ad esempio en, en-us, ru ecc.
Lunghezza del contenuto Indica il numero di byte della risposta. È utile solo quando il browser utilizza una connessione HTTP persistente (keep-alive)
Tipo di contenuto Indica il tipo MIME utilizzato per il documento
Scadenza Indica quando il documento scade e viene rimosso dal cache
Last-Modified Indica quando l'ultimo documento è stato modificato. Il client può memorizzare il documento e fornirlo in successivi richieste If-Modified-SinceIntestazione della richiesta
Posizione Entro 300 secondi, include tutte le risposte con un codice di stato, il browser si riconnetterà automaticamente e ricercherà il nuovo documento
Aggiorna Indica quanto spesso il browser richiede aggiornamenti della pagina.
Retry-After 与503 (Service Unavailable)一起使用,告知用户多久后请求将会得到响应
Set-Cookie 指明当前页面对应的cookie

HttpServletResponse类

response对象是javax.servlet.http.HttpServletResponse类的一个示例。就像服务器会创建request对象一样,它也会创建一个客户端响应。

response对象定义了处理创建HTTP信息头的接口。通过使用这个对象,开发者可以添加新的cookie、时间戳以及HTTP状态码等。

下表列出了由HttpServletResponse类提供用于设置HTTP响应头的方法:

S.N.方法 & 描述
1String encodeRedirectURL(String url) 对sendRedirect()方法使用的URL进行编码
2String encodeURL(String url) 对包含Session ID的URL进行URL编码,回传编码后的URL
3boolean containsHeader(String name) 返回指定的响应头是否存在
4boolean isCommitted() 返回响应是否已经提交到客户端
5void addCookie(Cookie cookie) 将指定的cookie添加到响应中
6void addDateHeader(String name, long date) 添加指定名称的响应头和日期值
7void addHeader(String name, String value) 添加指定名称的响应头和值
8void addIntHeader(String name, int value) 添加指定名称的响应头和int值
9void flushBuffer() 将任何缓存中的内容写入客户端
10void reset() 清除任何缓存中的任何数据,包括状态码和各种响应头
11void resetBuffer() 清除基本的缓存数据,不包括响应头和状态码
12void sendError(int sc) 向客户端发送一个使用指定状态码的错误响应,然后清除缓存
13void sendError(int sc, String msg) Send an error response to the client using the specified status code and message
14void sendRedirect(String location) Send a temporary indirect response to the client using the specified URL
15void setBufferSize(int size) Set the buffer size of the response body
16void setCharacterEncoding(String charset) Specify the response encoding set (MIME character set), for example UTF-8
17void setContentLength(int len) Specify the length of the response content in HTTP servlets, this method is used to set the HTTP Content-Length header
18void setContentType(String type) Set the response content type, if the response has not been committed
19void setDateHeader(String name, long date) Set the name and date of the response header using the specified name and date
20void setHeader(String name, String value) Set the name and content of the response header using the specified name and value
21void setIntHeader(String name, int value) Specify an int type value to the name header
22void setLocale(Locale loc) Set the response locale, if the response has not been committed
23void setStatus(int sc) Set the response status code

Example of HTTP response header program

The following example uses the setIntHeader() method and the setRefreshHeader() method to simulate a digital clock:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%
<%@ page import="java.io.*,java.util.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Base Tutorial Website (oldtoolbag.com)</title>
</head>
<body>
<h2>示例自动刷新</h2>
<%
   // 设置每隔5秒自动刷新
   response.setIntHeader("Refresh", 5);
   // 获取当前时间
   Calendar calendar = new GregorianCalendar();
   String am_pm;
   int hour = calendar.get(Calendar.HOUR);
   int minute = calendar.get(Calendar.MINUTE);
   int second = calendar.get(Calendar.SECOND);
   if(calendar.get(Calendar.AM_PM) == 0)
      am_pm = "AM";
   else
      am_pm = "PM";
   String CT = hour + ":" + minute + ":" + second + " " + am_pm;
   out.println("当前时间: " + CT + "\n");
%>
</body>
</html>

将以上代码保存为 main.jsp,然后通过浏览器访问它。它将会每隔5秒显示系统当前时间。

你也可以自己动手修改以上代码,试试使用其他的方法,这将能得到更深的体会。