|
Beginner’s Guide to Web Development – JSP Communication
This section of the tutorial covers communicating between JSP’s. One of the most common ways to accomplish this communication is via HTML forms.
Let’s start with an example. We will need to create two JSP’s for this. Type the following in your text editor and save it as
communication1.jsp in your c:\tomcat\webapps\examples\jsp\work\ folder.
<html>
<head>
<title>Communication Page One</title>
</head>
<body>
<form name="form" method="GET" action="communication2.jsp">
<br>
FIRST NAME:<input type="text" name="firstname" value="">
<br>
LAST NAME:<input type="text" name="lastname" value="">
<br>
<br>
<input type=submit>
</form>
</body>
</html>
Now, type the following in your text editor and save it as communication2.jsp
<html>
<head>
<title>Communication Page Two</title>
</head>
<body>
First Name: <% out.print ( request.getParameter("firstname") );%>
<br>
Last Name: <% out.print ( request.getParameter("lastname") );%>
</body>
</html>
Start up Tomcat if you haven’t already done so. Go to the following URL:
http://localhost:8080/examples/jsp/work/communication1.jsp
Type in a first and last name in the respective fields. Click the submit query button.
Notice that the text you typed into the fields on communication1.jsp are displayed on communication2.jsp.
Let’s go over the new material we’ve seen. Everything in communication1.jsp should be review. We’ve seen this is previous sections.
However, take note of the following line in communication2.jsp:
First Name: <% out.print ( request.getParameter("firstname") );%>
The new material here – request.getParameter("firstname") – makes use of a built in feature of JSP – the request object.
One of the methods available from the request object is the method getParameter (String <name of parameter>). When we submitted the
form communication1.jsp, we submitted two pieces of information, the firstname text and the lastname text. By submitting these pieces of
information, they are now available for extraction by the request.getParameter() method. All that we need to do is know what the
name of the piece of information we need is. In this case, we named the input types firstname and lastname on communication1.jsp.
Thus, we can pass either of these names into the getParameter() method, and the values corresponding to these names will be returned.
What we’ve learned is that we can pass information from one JSP page to another using HTML forms. We simply create a form, note the names we
gave to the input types, and submit the form. Then, the next page can read the values of the input types by calling the getParameter() method of
the built-in request object and passing in the name associated with the value we want to receive.
This concludes our coverage of JSP communication using HTML forms and the request object. Now we are going to talk about another
important built-in object of JSP: the Session object. The next part of the tutorial handles this topic.
|