242 CHAPTER 8 PERSISTENT COMMUNICATIONS PATTERN public (Simple web server)
242 CHAPTER 8 PERSISTENT COMMUNICATIONS PATTERN public void init(javax.servlet.ServletConfig config) throws javax.servlet.ServletException { _buffer = “”; _callCount = 0; } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException { ServletInputStream input = request.getInputStream(); byte[] bytearray = new byte[ request.getContentLength()]; input.read(bytearray); _buffer += new String(bytearray).toString(); _callCount ++; } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println(”Content (” + _buffer + “) Call Count (” + _callCount + “)(” + Calendar.getInstance().getTime() + “)”); } } Compared to the ClientCommunicator code, the ServerCommunicator is relatively simple, but that is due only to the nature of the global status resource implementation and the example in particular. The server-side implementation of the ServerCommunicatoris a minimal solution. As you can see in Figure 8-7, to implement the round trip, the servlet saves state in a data member (_buffer) and records the number of times the state has been modified (_callCount). The method init is called by the HTTP server and initializes the data members. The method doPost processes the HTTP POST request and is responsible for the writing stream implementation. From the perspective of the two-communication stream mechanism, the method doPost is called by the ClientCommunicator.send method. The data buffer that is sent to the server is read by using the method request.getInputStream. It is important to read the buffer as a stream of bytes because anything could be sent. The method doGet processes the HTTP GET request and is responsible for the reading stream implementation. The method doGet retrieves the state of the data members _bufferand _callCount that are concatenated to form a message sent to the client. From the perspective of the two-communication stream, the method doGet is called by the PrivateLoop function. Many readers will look at the code and be sticklers with respect to the implementation of doPost and doGet, and how the Java servlet is used. The implementations of doPost and doGet are not checking the MIME types and are violating the Permutations pattern. And the Java servlet is keeping state, although some readers might say that is kludgy coding. Fair enough, the critiques are noted and mentioned, but solving those critiques as a fully complete solution would add complexity to explaining the Persistent Communications pattern. To put it plainly, look at what the implementation is aiming to do, and write better code. Additionally, if you are
Searching for affordable and reliable webhost to host and run your web applications? Go to our java web server services and you will be pleased.