[ Team LiB ] |
Retrieving Form Variables in a ServletUp to this point, the discussion has centered around the request object in JSPs. The request object in a JSP is an instance of HttpServletRequest. In Hour 2, "JavaServer Pages Behind the Scenes," you saw servlets that received requests via the doGet method. This works fine for receiving form data via an HTTP GET request, but it will not work for data sent via an HTTP POST request. There are at least two other ways to receive a request in a servlet. First, you can implement a doPost method, which is invoked only if the browser posts data to the servlet. Second, you can implement the service method, which receives data whether it was sent via a GET or a POST request. It is best to receive form data via the service method, because it lets you send data to the servlet via GET or POST. By implementing only doGet or only doPost, you limit the ways to access the servlet. The service method, just like doGet and doPost, takes an HttpServletRequest and an HttpServletResponse as parameters. The HttpServletRequest is the same object as the request object in a JSP. This means, of course, that you already know how to retrieve form variables in a servlet because you do it the same way you do in a JSP. Handling GET and POST with doPost
Listing 3.6 shows a servlet version of the ShowParameters JSP you saw in Listing 3.5. Again, you can test it out by passing parameters directly in the URL. Listing 3.6 Source Code for ShowParametersServlet.java
The output from ShowParametersServlet is identical to the output from the ShowParameters JSP. In fact, the core part of both programs is the same. The only difference is the code to print out the beginning and ending HTML tags. |
[ Team LiB ] |
No comments:
Post a Comment