The following example shows 2 methods to navigate from one servlet to another servlet or html or jsp page.
In this example the user selects a color and accordingly goes to the respective page.
Step 1 : Create a startup HTML or JSP page.
Enter the following code in the body tag of the page.
//create a drop down list to allow user to select their choice.
<form action="servlet1">
<select name="color">
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
<input type="submit" value="Go!"/>
</form>
When User clicks the "Go!" the control of the application will pass to the servlet
Step 2 : Create a servlet (in my case named "servlet1")
Enter the following code in the doGet() method of the servlet
//assuming request as the object of the HttpServletRequest Class.
//assuming response as the object of the HttpServletResponse Class.
//accept user input and store it into a String variable.
String option = request.getParameter("color");
//following code shows 2 methods to go to another page or servlet.
//check the value selected by the user and pass the control to the respective page.
if(option.equals("red")){
//Method 1
RequestDispatcher rd = request.getRequestDispatcher("red.html");
rd.forward(request, response);
} else if (option.equals("blue")){
//Method 2
response.sendRedirect("blue.html");
}
Step 3 : Create Result files
Enter the following code in the body tag of the "red.html" file
<h1>Red</h1>
Enter the following code in the body tag of the "blue.html" file
<h1>Blue</h1>
great
ReplyDelete