JSP Form Handling - Beginner Exercises
Objective
Practice form handling in JSP using [Link]() and form components like textboxes, radio
buttons, and checkboxes.
Exercise 1: Simple Greeting Form
Create a form that accepts a user's name and displays a greeting message.
- Use a <form> with method="post".
- Use [Link]() in the result page.
Form Page: [Link]
<form action="greet_result.jsp" method="post">
Enter your name: <input type="text" name="username">
<input type="submit" value="Greet">
</form>
Result Page: greet_result.jsp
<%
String name = [Link]("username");
%>
<p>Hello, <%= name %>!</p>
Exercise 2: Basic Calculator
Create a calculator that accepts two numbers and displays their sum.
Form Page: [Link]
<form action="calc_result.jsp" method="post">
Number 1: <input type="text" name="num1"><br>
JSP Form Handling - Beginner Exercises
Number 2: <input type="text" name="num2"><br>
<input type="submit" value="Add">
</form>
Result Page: calc_result.jsp
<%
int a = [Link]([Link]("num1"));
int b = [Link]([Link]("num2"));
int sum = a + b;
%>
<p>Sum: <%= sum %></p>
Exercise 3: Gender and Hobby Form
Create a form to collect gender (radio) and hobbies (checkbox). Display selected values.
Form Page: [Link]
<form action="hobby_result.jsp" method="post">
Gender:<br>
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female<br><br>
Hobbies:<br>
<input type="checkbox" name="hobby" value="Reading"> Reading
<input type="checkbox" name="hobby" value="Music"> Music
<input type="checkbox" name="hobby" value="Travel"> Travel<br><br>
<input type="submit" value="Submit">
</form>
JSP Form Handling - Beginner Exercises
Result Page: hobby_result.jsp
<%
String gender = [Link]("gender");
String[] hobbies = [Link]("hobby");
%>
<p>Gender: <%= gender %></p>
<p>Hobbies:</p>
<ul>
<%
if (hobbies != null) {
for (String h : hobbies) {
%>
<li><%= h %></li>
<%
} else {
%>
<li>No hobbies selected.</li>
<%
%>
</ul>