getAttribute () - Передача данных с сервера на JSP
Предположим, что некоторые данные на стороне сервера были созданы, и теперь для передачи этой информации на странице JSP необходим метод request.getAttribute (). Фактически это отличает методы getAttribute () и getParameter (). Последний используется для передачи данных на стороне клиента в JSP.
Реализация
1) Сначала создайте данные на стороне сервера и передайте их JSP. Здесь будет создан список ученических объектов в сервлете, который будет передан в JSP с помощью setAttribute ().
2) Затем JSP получит отправленные данные с помощью getAttribute ().
3) Наконец, JSP отобразит полученные данные в табличной форме.
Servlet to create data and dispatch it to a JSP : StudentServlet.java
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"; }} |
JSP to retrieve data sent by servlet “StudentServlet.java” and display it : stdlist.jsp
<%@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> |
Класс Student.java
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; }} |
Запуск приложения
1) Запустите сервлет «StudentServlet.java», который передаст данные об учащемся на страницу JSP «stdlist.jsp».
2) Страница JSP «stdlist.jsp» извлекает данные и отображает их в табличной форме.
Примечание. Все приложение разработано и протестировано в среде IDE NetBeans 8.1.
Выход
Отображение данных учащихся: stdlist.jsp