top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How does a servlet communicate with a JSP page?

+3 votes
762 views
How does a servlet communicate with a JSP page?
posted Jan 31, 2015 by Amit Kumar Pandey

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

0 votes

using RequestDispatcher, we will forward or include JSP and then using implicit object 'request' we can use all states of caller servlet.

RequestDispatcher rd=request.getRequestDispatcher("URL");
rd.forward(request, response);

answer Feb 2, 2015 by Garima Gupta
0 votes

The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing.

public void doPost (HttpServletRequest request,
HttpServletResponse response) {

              try {
                govi.FormBean f = new govi.FormBean();
                String id = request.getParameter("id");
                f.setName(request.getParameter("name"));
                f.setAddr(request.getParameter("addr"));
                f.setAge(request.getParameter("age"));
                          //use the id to compute
                          //additional bean properties like info
                           //maybe perform a db query, etc.
                          // . . .
                          f.setPersonalizationInfo(info);
                request.setAttribute("fBean",f);
                getServletConfig().getServletContext().getRequestDispatcher
                                          ("/jsp/Bean1.jsp").forward(request, response);
              } catch (Exception ex) {
                . . .
              }
           }

The JSP page Bean1.jsp can then process fBean, after first extracting it from the default request scope via the useBean action.

         <jsp:useBean id="fBean" class="govi.FormBean" scope="request"/>
          <jsp:getProperty name="fBean" property="name" />
          <jsp:getProperty name="fBean" property="addr" />
          <jsp:getProperty name="fBean" property="age" />
          <jsp:getProperty name="fBean" property="personalizationInfo" />
answer Sep 21, 2015 by Karthick.c
...