getAttribute() – Passing data from Server to JSP

Suppose some data at the Server side has been created and now in order to pass that information in a JSP page, there is a need of request.getAttribute() method. This, in fact differentiates the getAttribute() and getParameter() methods. The latter is used to pass Client side data to a JSP.

Implementation
1) First create data at the server side and pass it to a JSP. Here a list of student objects in a servlet will be created and pass it to a JSP using setAttribute().
2) Next, the JSP will retrieve the sent data using getAttribute().
3) Finally, the JSP will display the data retrieved, in a tabular form.

Servlet to create data and dispatch it to a JSP : StudentServlet.java

filter_none

edit
close

play_arrow

link
brightness_4
code

package saagnik;
  
import java.io.*;
import java.util.ArrayList;
import javax.servlet.*;
import javax.servlet.http.*;
  
public class StudentServlet extends HttpServlet {
  
  protected void processRequest(HttpServletRequest request,
                                HttpServletResponse response)
    throws ServletException, IOException
    {
     response.setContentType("text/html;charset=UTF-8");
     try (PrintWriter out = response.getWriter()) {
       out.println("<!DOCTYPE html>");
       out.println("<html>");
       out.println("<head>");
       out.println("<title>Servlet StudentServlet</title>");
       out.println("</head>");
       out.println("<body>");
  
       // List to hold Student objects
       ArrayList<Student> std = new ArrayList<Student>();
  
       // Adding members to the list. Here we are 
       // using the parameterized constructor of 
       // class "Student.java"
       std.add(new Student("Roxy Willard", 22, "B.D.S"));
       std.add(new Student("Todd Lanz", 22, "B.Tech"));
       std.add(new Student("Varlene Lade", 21, "B.B.A"));
       std.add(new Student("Julio Fairley", 22, "B.Tech"));
       std.add(new Student("Helena Carlow", 24, "M.B.B.S"));
  
       // Setting the attribute of the request object
       // which will be later fetched by a JSP page
         request.setAttribute("data", std);
  
       // Creating a RequestDispatcher object to dispatch
       // the request the request to another resource
         RequestDispatcher rd = 
             request.getRequestDispatcher("stdlist.jsp");
  
       // The request will be forwarded to the resource 
       // specified, here the resource is a JSP named,
       // "stdlist.jsp"
          rd.forward(request, response);
            out.println("</body>");
            out.println("</html>");
        }
    }
    /** Following methods are used to handle
        requests coming from the Http protocol request.
        Inspects method of HttpMethod type
        and if the request is a POST, the doPost() 
        method will be called or if it is a GET,
        the doGet() method will be called. 
    **/
    @Override
    protected void doGet(HttpServletRequest request,
                        HttpServletResponse response)
        throws ServletException, IOException
    {
        processRequest(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request,
                        HttpServletResponse response)
        throws ServletException, IOException
    {
        processRequest(request, response);
    }
    @Override
    public String getServletInfo()
    {
        return "Short description";
    }
}

chevron_right


JSP to retrieve data sent by servlet “StudentServlet.java” and display it : stdlist.jsp

filter_none

edit
close

play_arrow

link
brightness_4
code

<%@page import="saagnik.Student"%>
<%@page import="java.util.ArrayList"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
  <head>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   <title>Student List</title>
  </head>
  <body>
      <h1>Displaying Student List</h1>
      <table border ="1" width="500" align="center">
         <tr bgcolor="00FF7F">
          <th><b>Student Name</b></th>
          <th><b>Student Age</b></th>
          <th><b>Course Undertaken</b></th>
         </tr>
        <%-- Fetching the attributes of the request object
             which was previously set by the servlet 
              "StudentServlet.java"
        --%> 
        <%ArrayList<Student> std = 
            (ArrayList<Student>)request.getAttribute("data");
        for(Student s:std){%>
        <%-- Arranging data in tabular form
        --%>
            <tr>
                <td><%=s.getName()%></td>
                <td><%=s.getAge()%></td>
                <td><%=s.getCrs()%></td>
            </tr>
            <%}%>
        </table
        <hr/>
    </body>
</html>

chevron_right


The Student.java class



filter_none

edit
close

play_arrow

link
brightness_4
code

package saagnik;
  
public class Student {
    private int age;
    private String name;
    private String crs;
    // Parameterized Constructor to set Student
    // name, age, course enrolled in.
    public Student(String n, int a, String c)
    {
        this.name = n;
        this.age = a;
        this.crs = c;
    }
    // Setter Methods to set table data to be
    // displayed
    public String getName() { return name; }
    public int getAge() { return age; }
    public String getCrs() { return crs; }
}

chevron_right


Running the application
1) Run the servlet “StudentServlet.java”, which will pass student data to JSP page “stdlist.jsp”.
2) The JSP page “stdlist.jsp” retrieves the data and displays it in a tabular form.

Note : Entire application has been developed and tested on NetBeans IDE 8.1

Output
Displaying Student Data : stdlist.jsp
Displaying Student data



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.