Let's take a look at the following example:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BufferedInputStream is = new BufferedInputStream(request.getInputStream()); InputStreamReader isr = new InputStreamReader(is); int character; StringBuffer process = new StringBuffer(); while((character = isr.read()) != -1) { process.append((char)character); } System.out.println(process); } catch...
Looking at the code, notice that the first thing we're doing is calling the doGet() method from the doPost() method. We do this as a simple way to redirect all incoming data to the same code. We then create a BufferedInputStream object is from the request.getInputStream() method. From is we've created an InputStreamReader object isr in order to read the inputstream. Next we create a StringBuffer object process and fill it with the characters we read from the inputstream...for those of you who've used inputstreams this code should look very familar. Finally we do something with process.
Why would you ever want to do this? One example of of using this technique is when you want to turn a servlet into a webservice. I'm currently working on a how-to article on this subject. Look for it shortly.
5 comments:
Unless I'm mistaken, this approach still requires the non-HTTP client to preface requests with an HTTP header minimally containing the HTTP version and HTTP URL so that the servlet container could even get the request to the servlet. Additionally, the non-HTTP client would still have to know about HTTP response codes. Is there another way to use a servlet (perhaps a Filter or GenericServlet) that can be used to handle non-HTTP messages? Thanks.
You're right. The title of this post is somewhat misleading. The example I was thinking of when I created this was for processing XML data instead of HTML data. If there was no need to use an app server, I would probably create a server side java program that contained a socket listener for client interaction.
Rick.
Do you have a sample of this that I can deploy into Tomcat or Jboss? Thanks in advance. Appreciate your help.
Very informative article.
I'm not sure I understand your question. If you completed the servlet code it could be deployed with Tomcat or JBoss.
I managed to deploy the application using your code. Thanks.
Post a Comment