out.println & request.getParameterTo display any content to web browser, you can use "out.println".
The syntax is:
<%
out.println "This is my first JSP page.";
%>
There is another method to do the same work using "<%=" and "%>":
<%=This is my first JSP page.%>
The output is the same:
This is my first JSP page.
Please notice that, if using "out.println" to display the content,
we must use double quotes; if using the second method, there are no quotes needed.
To understand request.getParameter, let's create two JSP pages:
first.JSP:
<html>
<body>
<a href="second.JSP?user=John">Send Query String</a>
<form action="second.JSP" method="post">
<input type="text" name="user">
<input type="submit" value="Send Query String">
</form>
</body>
</html>
second.JSP:
<html>
<body>
Hi <%out.println request.getParameter("user");%>
</body>
</html>
Save the two pages in the same folder and open first.JSP on web browser. Click
the link "Send Query String", you will see second.JSP come out and
show the value "John":
Hi John
Back to first.JSP. If you enter a value "Mike" in the text box, and
click the button "Send Query String", you will see the value "Mike"
displayed in second.JSP:
Hi Mike
To retrieve the query string, we use request.getParameter. The syntax is:
request.getParameter("<query string name>");
For example:
request.getParameter("user")
To display this to a web page, we must use "out.println" or "<%=%>":
<%out.println request.getParameter("user");%>
<%=request.getParameter("user");%>
To send a query string out, we should notice three points:
- Where do you want the query string sent to;
- What is the name of the query string;
- What is the value of the query string.
You can use a link or a form to send a query string out. In the above sample,
we point the query string to a destination page "second.JSP", give
the query string a name "user" and a value "John".
<a href="second.JSP?user=John">Send Query String</a>
Please notice that the express "second.JSP?user=John" means: send
query string named "user" and it's value "John" to the page
named "second.JSP". This work can be done by a form:
<form action="second.JSP" method="post"> --------- destination
<input type="text" name="user"> --------- name and value
<input type="submit" value="Send Query String">
</form>
There is an advantage for using form to send query string that you can enter
any value into the text box without change the code in the page.
As you see, JSP can do something that can not be done by HTML. With HTML, you
can not sent data from one page to another page, but JSP can do this work.
|