CSC419 ยท 2081 ยท 5 marks
Write a program in JSP to display the string taken in one page in another page.
Write a program in JSP to display the string taken in one page in another page. [5]
Advanced Java ProgrammingChapter 7: Servlets and Java Server pagesServlet vs JSP, JSP Access Model, JSP Syntax
Quick answer
The string is passed from one page to another using the HTML form's action attribute and retrieved using JSP's built-in request.getParameter() method.
JSP Program to Display String from One Page to Another Page
Concept
This program uses two JSP pages:
- Page 1 (
input.jsp): Contains an HTML form with a text field where the user enters a string. - Page 2 (
display.jsp): Receives the string via HTTP request and displays it.
Page 1: input.jsp
<%-- input.jsp : Takes string input from the user --%>
<html>
<head>
<title>Input Page</title>
</head>
<body>
<h2>Enter a String</h2>
<form action="display.jsp" method="post">
Enter String:
<input type="text" name="userString" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Explanation:
| Element | Purpose |
|---|---|
action="display.jsp" | Sends form data to display.jsp |
method="post" | Sends data via HTTP POST method |
name="userString" | Name used to retrieve value in next page |
Page 2: display.jsp
<%-- display.jsp : Displays the string received from input.jsp --%>
<html>
<head>
<title>Display Page</title>
</head>
<body>
<h2>Received String</h2>
<%
// Retrieve the string sent from input.jsp
String str = request.getParameter("userString");
// Check if string is not null or empty
if (str != null && !str.isEmpty()) {
%>
<p>The string entered is: <strong><%= str %></strong></p>
<%
} else {
%>
<p>No string was entered.</p>
<%
}
%>
<a href="input.jsp">Go Back</a>
</body>
</html>
Explanation:
| Code | Purpose |
|---|---|
request.getParameter("userString") | Retrieves the value of the text field named userString from Page 1 |
<%= str %> | JSP expression tag to display the value on the page |
| Null check | Prevents errors if no input is provided |
Output
Page 1 (input.jsp):
Enter a String
Enter String: [ Hello TU ] [Submit]
Page 2 (display.jsp) after clicking Submit:
Received String
The string entered is: Hello TU
[Go Back]
Key Points to Remember
requestis a built-in JSP implicit object of typeHttpServletRequest.request.getParameter("name")returns the value as a String.method="post"is preferred overmethod="get"to avoid showing data in the URL.- JSP scriptlet tags
<% %>are used for Java code and<%= %>for output expressions.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.