Program to demonstrate working of RequestDispatcher in a servlet for forwarding the request to the correct JSP
subscribe.html
CustomerInfoDispatcher.java
customer_info.jsp
Customer.java
Output of the program :
subscribe.html
customer_info.jsp
subscribe.html
|
CustomerInfoDispatcher.java
package com.hubberspot.jsp.servlets.examples; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.hubberspot.model.Customer; import com.hubberspot.utility.CustomerService; @WebServlet("/CustomerInfoDispatcher") public class CustomerInfoDispatcher extends HttpServlet { protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { doPost(request,response); } protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { // Get the form requests String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); String emailAddress = request.getParameter("emailAddress"); // Using DataModel in a Servlet Customer customer = new Customer(firstName, lastName, emailAddress); // storing the Customer object in the request object request.setAttribute("Customer", customer); String url = "/customer_info.jsp"; // forwarding request and response object to a JSP page // Using RequestDispatcher Object RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url); dispatcher.forward(request, response); } }
customer_info.jsp
|
Customer.java
package com.hubberspot.model; public class Customer { private String firstName; private String lastName; private String emailAddress; public Customer() { firstName = ""; lastName = ""; emailAddress = ""; } public Customer(String firstName , String lastName , String emailAddress) { this.firstName = firstName; this.lastName = lastName; this.emailAddress = emailAddress; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmailAddress() { return emailAddress; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } }
Output of the program :
subscribe.html
customer_info.jsp