Example: Running the command in the servlet
The CommandTarget interface declares one method, executeCommand, which the client implements. The executeCommand method takes a TargetableCommand object as input; it also returns a TargetableCommand.
Running the command in the servlet
The servlet that runs the command is shown in the following example. The service method retrieves the command from the input stream and runs the performExecute method on the command. The resulting object, with any output properties that must be returned to the client, is placed on the output stream and sent back to the client.
... 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(); } } }The target invokes the performExecute method on the command, but this is not always necessary. In some applications, it can be preferable to implement the work of the command locally. For example, the command can be used only to send input data, so that the target retrieves the data from the command and runs a local database procedure based on the input. You must decide the appropriate way to use commands in your application.
Related tasks
Use a command
Related Reference
Example: Implementing a client-side adapter
Example: Writing a command target (client-side adapter)
Reference topic