CommandTarget インターフェースは、クライアントが実装する 1 つのメソッド executeCommand を 宣言します。executeCommand メソッドは、TargetableCommand オブジェクトを入力として 取り、また TargetableCommand を戻します。
コマンドを実行するサーブレットは、 以下の例に示されます。サービス・メソッドは入力ストリームからコマンドを検索し、 コマンド上で performExecute メソッドを実行します。 結果のオブジェクトは、クライアントへ戻される必要がある出力プロパティーを持ち、 出力ストリーム上に配置され、クライアントに戻されます。
... import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import com.ibm.websphere.command.*; public class CommandServlet extends HttpServlet { ... public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ... // Create input and output streams InputStream inputStream = request.getInputStream(); OutputStream outputStream = response.getOutputStream(); // Retrieve the command from the input stream ObjectInputStream objectInputStream = new ObjectInputStream(inputStream); TargetableCommand command = (TargetableCommand) objectInputStream.readObject(); // Create the command for the return stream Object returnObject = command; // Try to run the command's performExecute method try { command.performExecute(); } // Handle exceptions from the performExecute method ... // Return the command with any output properties ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); objectOutputStream.writeObject(returnObject); // Flush and close output streams ... } catch(Exception ex) { ex.printStackTrace(); } } }
ターゲットはコマンド上で performExecute メソッドを呼び出しますが、 これは常に必要ではありません。一部のアプリケーションでは、コマンドの作業をローカ ルに実装することが望ましい場合があります。例えば、コマンドは入力データを送信するためだけに 使用できます。そのため、ターゲットはコマンドからデータを検索し、 入力に基づくローカル・データベース・プロシージャーを実行します。アプリケーション内でコマンドを使用する 適した方法を決定する必要があります。