1

I got a question about servlets and jsp.

Servlet:

public class Servlet extends javax.servlet.http.HttpServlet {

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        Integer i = new Integer(15);
        request.setAttribute("var", i);
        RequestDispatcher Dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
        Dispatcher.forward(request, response);
    }

JSP page:

<html>
  <head>
    <title></title>
  </head>
  <body>
        <form id="id" method="get" action="servlet">
            <%= (request.getAttribute("var")) %>
        </form>
  </body>
</html>

As a result I expect to see 15, but I see null. Why does it happen?

Green Fireman
  • 617
  • 1
  • 11
  • 27

3 Answers3

5

Request parameters are sent from the view to the controller, request attributes are used to pass data in the current request to help build the new response. So, you should not use scriplets and access to the request attributes by using Expression Language:

<body>
    <!-- No need to use a form for this page -->
    The request attribute: ${var}
</body>

Note that by your current request, you should perform a GET request on your servlet. Since your servlet name is servlet (which I suggest your to change it immediately), you should access to this URL: http://yourServerName/yourApplicationName/servlet

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
0

Use request.getAttribute("var");

AzAh
  • 41
  • 1
  • 1
  • 14
0

I don't know in the servlet but in struts 2 you need getter and setter method to sent data from jsp, you try this:

public class Servlet extends javax.servlet.http.HttpServlet 
{
    private Integer i;
    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        i = new Integer(15);
        request.setAttribute("var", i);
        RequestDispatcher Dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
        Dispatcher.forward(request, response);
    }

  public Integer getI()
  {
     return i;
  }
  public void setI(Integer i)
  {
    this.i = i;
   }

 }//also lacked this 
Premier
  • 766
  • 2
  • 10
  • 20