HttpServletクラスとメソッド

広告

ではサーブレットの基本となる「HttpServlet」クラスを見てみます。

クラス定義は下記のようになっています。

java.lang.Object
  javax.servlet.GenericServlet
    javax.servlet.http.HttpServlet

public abstract class HttpServlet
extends GenericServlet
implements java.io.Serializable

「HttpServlet」クラスは「GenericServlet」クラスのサブクラスです。一応「GenericServlet」クラスの定義も見ておきます。

java.lang.Object
  javax.servlet.GenericServlet

public abstract class GenericServlet
extends java.lang.Object
implements Servlet, ServletConfig, java.io.Serializable

サーブレットは「Servlet」インターフェースを実装する必要がありますが「GenericServlet」クラスで実装が行われています。

HttpServletクラスのメソッド

「HttpServlet」クラスでは多くのメソッドが定義されています。リクエストのHTTPメソッドの種類毎に対応するメソッドがそれぞれ用意されています。

HTTPメソッドメソッド
GETprotected void doGet(HttpServletRequest req, HttpServletResponse resp)
POSTprotected void doPost(HttpServletRequest req, HttpServletResponse resp)
PUTprotected void doPut(HttpServletRequest req, HttpServletResponse resp)
DELETEprotected void doDelete(HttpServletRequest req, HttpServletResponse resp)
HEADprotected void doHead(HttpServletRequest req, HttpServletResponse resp)
TRACEprotected void doTrace(HttpServletRequest req, HttpServletResponse resp)
OPTIONSprotected void doOptions(HttpServletRequest req, HttpServletResponse resp)

「HttpServlet」クラスを継承したクラスは、このどれかのメソッドを最低1つは実装する必要があります。もし複数のHTTPメソッドで呼び出される可能性がある場合は複数のメソッドを実装することも可能です。

HTTPメソッドの中でも主に使われるのは「GET」と「POST」です。そこで「doGet」メソッドと「doPost」メソッドについて見てみます。

「doGet」メソッド:

Called by the server (via the service method) to allow a servlet to 
handle a GET request.

Parameters:
  req - an HttpServletRequest object that contains the request the 
    client has made of the servlet
  resp - an HttpServletResponse object that contains the response
    the servlet sends to the client 
Throws: 
  java.io.IOException - if an input or output error is detected when
    the servlet handles the GET request 
  ServletException - if the request for the GET could not be handled

「doPost」メソッド:

Called by the server (via the service 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. 

Parameters:
  req - an HttpServletRequest object that contains the request the 
    client has made of the servlet
  resp - an HttpServletResponse object that contains the response
    the servlet sends to the client 
Throws: 
  java.io.IOException - if an input or output error is detected when
    the servlet handles the request 
  ServletException - if the request for the POST could not be handled

「GET」メソッドはクライアントからページの要求を行う場合に使われます。直接サーブレット名をURLに指定して表示したりリンクに設定されたサーブレットをクリックした場合には「GET」を使ってリクエストが来ます。またフォームにおいて送信方法に「GET」を使った場合にも「GET」メソッドが使われます。

「POST」メソッドはクライアントからデータを送る場合に使われます。主にフォームにおいて送信方法に「POST」を指定した場合に使われます。

実際にどのように使うかについては次のページを参照して下さい。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。