Java EE 107 Request Dispatcher Method
This tutorial is based on http://www.youtube.com/watch?v=8cvdgJ94r5M
STEPS
1) Run Eclipse.
2) Open The Project “ServletJSPExample”.
3) Edit “ServletExample.java”
3.1) Add getRequestDispatcher method.
3.2) Outcome (getRequestDispatcher)
3.3) Add statement to evaluate if input parameter is empty
3.3) Outcome (Null parameter input check)
3.4) Add New JSP file.
3.5) Type the name “output.jsp”
3.6) Select Template “New JSP File (xhtml)”.
3.7) Insert output statements into <body> element:
3.8) Edit ServletExample.java to forward request/response to output.jsp
3.9) Outcome (complete data entry will get data display)
4) ADDITIONAL: Submit the form using Get Method instead of Post Method
4.1) Edit “index.jsp”
4.2) Observe the outcome.
getServletContext().getRequestDispatcher("/index.jsp").forward(request, response); |
if (request.getParameter("firstname")==null || request.getParameter("lastname")==null){ getServletContext().getRequestDispatcher("/index.jsp").forward(request, response); return; } |
Or
if (request.getParameter("firstname").equals="" || request.getParameter("lastname").equals=""){ getServletContext().getRequestDispatcher("/index.jsp").forward(request, response); return; } |
Empty input will be forwarded to index.jsp
Non-empty input will get the input parameter displayed on screen.
<h1> Your first and last name is:</h1> <% String firstName=(String) request.getAttribute("firstname"); String lastName=(String) request.getAttribute("lastname"); out.println(firstName + " " + lastName); %> |
1) Delete the statement “PrintWriter out=response.getWriter();”
2) Replace the statement “out.println(firstName + " " + lastName);” with the following codes:
request.setAttribute("firstName", firstName); request.setAttribute("lastName", lastName); getServletContext().getRequestDispatcher("/output.jsp").forward(request,response); |
4) ADDITIONAL: Submit the form using Get Method instead of Post Method
4.1) Edit “index.jsp”
Replace the statement “method="post"” in the <form> element with the following codes:
“method="get"” |
4.2) Observe the outcome.
Enter values in the input fields.
Observe that the input parameters are shown in the URL box.
ADDITIONAL REFERENCES:
Read more: http://www.tutorialspoint.com/servlets/servlets-life-cycle.htm
Read more: http://www3.ntu.edu.sg/home/ehchua/programming/java/javaservlets.html