Servlet HTTP status code


The format of HTTP request and HTTP response messages is similar, and the structure is as follows:

  • Initial status line + carriage return and line feed (carriage return + line feed)

  • Zero or more header lines + carriage return and line feed characters

  • One blank line, that is, carriage return and line feed character

  • An optional message body, such as a file, query data, or query output

For example, the server's response header looks like this:

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

Status line Includes the HTTP version (in this case, HTTP/1.1), a status code (in this case, 200), and a short message corresponding to the status code (in this case, OK).

The following is a list of HTTP status codes and related information that may be returned from the web server:

##204No Content 205Reset Content206Partial Content300Multiple ChoicesLink list. Users can select a link to go to that location. Up to five addresses. 301Moved PermanentlyThe requested page has been moved to a new URL. 302FoundThe requested page has been temporarily moved to a new URL. 303See OtherThe requested page can be found under a different URL. 304Not Modified305Use Proxy306This code was used in previous versions. It is no longer used, but the code remains. 307Temporary RedirectThe requested page has been temporarily moved to a new URL. 400Bad RequestThe server does not understand the request. 401UnauthorizedThe requested page requires a username and password. 402Payment Required403ForbiddenAccess to the requested page is prohibited. 404Not FoundThe server cannot find the requested page. .405Method Not AllowedThe method specified in the request is not allowed.##500Internal Server ErrorOutstanding request. The server encountered an unexpected situation. 501Not ImplementedIncomplete request. The server does not support the required functionality. 502Bad GatewayIncomplete request. The server received an invalid response from the upstream server. 503Service UnavailableIncomplete request. The server is temporarily overloaded or down. 504Gateway TimeoutGateway timeout. 505HTTP Version Not SupportedThe server does not support the "HTTP protocol" version.

Methods to set HTTP status codes

The following methods can be used to set HTTP status codes in Servlet programs. These methods are available through the HttpServletResponse object.

CodeMessageDescription
100Continue Only part of the request has been received by the server, but as long as it has not been rejected, the client should continue with the request.
101Switching ProtocolsServer switching protocol.
200OKThe request was successful.
201CreatedThe request is complete and creates a new resource.
202AcceptedThe request was accepted for processing, but the processing was incomplete.
203Non-authoritative Information
Unused
You cannot use this code yet.
406Not AcceptableThe server only generates a response that is not accepted by the client.
407Proxy Authentication RequiredYou must use proxy server authentication before the request is served.
408Request TimeoutThe request took longer than the server could wait and timed out.
409ConflictThe request could not be completed due to a conflict.
410GoneThe requested page is no longer available.
411Length Required"Content-Length" is not defined. The server cannot handle request information sent by the client without Content-Length.
412Precondition FailedThe precondition given in the request was evaluated by the server as false.
413Request Entity Too LargeThe server does not accept the request because the request entity is too large.
414Request-url Too LongThe server did not accept the request because the URL was too long. Occurs when you convert a "post" request into a "get" request with long query information.
415Unsupported Media TypeThe server did not accept the request because the media type is not supported.
417Expectation Failed
Serial numberMethod & Description
1public void setStatus (int statusCode)
This method sets an arbitrary status code. The setStatus method accepts an int (status code) as a parameter. If your reaction contains a special status code and documentation, make sure to call setStatus before actually returning anything using PrintWriter.
2public void sendRedirect(String url)
This method generates a 302 response along with a new document URL Location Header.
3public void sendError(int code, String message)
This method sends a status code (usually 404), Together with a short message that is automatically formatted inside the HTML document and sent to the client.

HTTP status code example

The following example sends the 407 error code to the client browser, and the browser will display "Need authentication! !!" information.

// 导入必需的 java 库
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// 扩展 HttpServlet 类
public class showError extends HttpServlet {
 
  // 处理 GET 方法请求的方法
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // 设置错误代码和原因
      response.sendError(407, "Need authentication!!!" );
  }
  // 处理 POST 方法请求的方法
  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
     doGet(request, response);
  }
}

Now, calling the above Servlet will display the following results:

##HTTP Status 407 - Need authentication!!!

type Status report

message Need authentication!!!

description The client must first authenticate itself with the proxy (Need authentication!!!).

Apache Tomcat/5.5.29