The Next Servlet: The Request and the Response
April 5, 2000
The Request object facilitates parameter passing from the client
(web browser) to the server (servlet). The 'getParameter' method
is used to get the parameters passed.
Let us say we have following HTML code:
<HTML>
<HEAD>
<TITLE> Request Object </TITLE>
</HEAD>
<BODY>
<FORM METHOD="POST" ACTION="/servlet/WelcomeServlet">
Enter your Name: <INPUT TYPE=TEXT NAME="myName">
<INPUT TYPE="SUBMIT" VALUE="Send Name">
</FORM>
</BODY>
</HTML>
We will write a simple servlet: WelcomeServlet to get the name
from the HTML form and display a personalized welcome message.
When this form submits (user presses the submit button) the input
field 'myName' (and all the other input fields, if there are any)
is passed to the Servlet as part of the Request object.
We can access individual fields by :
String Name = request.getParameter("myName");
To write back to the browser we use the Response object
The getWriter method of the Response object can be used to 'print'
the response to the browser.
PrintWriter out = response.getWriter();
out.println("Welcome " + Name + " !");
So the complete code is :
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String Name = request.getParameter("myName");
PrintWriter out = response.getWriter();
out.println("Welcome " + Name + " !");
}
}
Note this time we are writing doPost as the form is using
ACTION=POST.
Servlet
Building Web Applications Using Servlets and JSP
HTML Generation
|