Java Reference
In-Depth Information
14.
After the nested
ifs
, add the following statement:
dispatcher.forward(req, resp);
The
RequestDispatcher
object's forward method will send the request and response directly to the JSP that
was specified in the
if
statements. By invoking the JSPs from the servlet, we have taken the browser “out of the loop”
thereby speeding up access to the JSPs.
The EmpServlet source code should look like the following:
import
java.io.IOException;
import
javax.servlet.ServletException;
import
javax.servlet.annotation.WebServlet;
import
javax.servlet.http.HttpServlet;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;
import
javax.servlet.RequestDispatcher;
public class
EmpServlet
extends
HttpServlet {
private static final long
serialVersionUID
= 1L;
RequestDispatcher dispatcher;
public
EmpServlet(){
super
();
}
protected void
doGet(HttpServletRequest req,
HttpServletResponse resp)
throws
ServletException, IOException {
}
protected void
doPost(HttpServletRequest req,
HttpServletResponse resp)
throws
ServletException, IOException {
String Function = req.getParameter("functionLB");
if
(Function.equals("Display")) {
dispatcher =
getServletContext().getRequestDispatcher("DispEmpInfoJSP.jsp");
}
else
{
if
(Function.equals("Gross")) {
dispatcher =
getServletContext().getRequestDispatcher("DispEmpGrossJSP.jsp");
}
else
{
if
(Function.equals("TaxAmt")) {
dispatcher =
getServletContext().getRequestDispatcher("DispEmpTaxAmtJSP.jsp");
}
}
}
dispatcher.forward(req, resp);
}
}
15.
Save the EmpServlet source code.
16.
Run c9/EnterEmpInfoForm on the server and verify that all three JSPs are
displayed as expected.