Bài 2: hướng dẫn truyền dữ liệu từ Servlet và hiển thị trên JSP

hướng dẫn truyền dữ liệu từ Servlet và hiển thị trên JSP

1. Cách truyền dữ liệu từ Servlet sang JSP

Tạo dự án mới

Theo các bước như bài 1, Đặt tên dự án là: data_tranfer

Ví dụ 1 cơ bản: Tạo Servlet, ví dụ đặt tên là DemoServlet

Sau đó khai báo code có dạng sau

@WebServlet("/demo")
public class DemoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        // Truyền dữ liệu cơ bản
        request.setAttribute("msg", "Xin chào từ Servlet!");
        
        // Truyền mảng
        String[] fruits = {"Táo", "Cam", "Chuối"};
        request.setAttribute("fruits", fruits);
        
        // Chuyển sang JSP
        request.getRequestDispatcher("/demo.jsp").forward(request, response);
    }
}

2. Hiển thị dữ liệu cơ bản trong JSP

Mở file src/main/webapp/demo.jsp

<h2>Dữ liệu cơ bản:</h2>
<p>${msg}</p>

Ở đây dùng EL (Expression Language) ${...} để lấy giá trị thay vì <%= %>.

Chạy serve: Click phải chuột vào thư mục dự án, chọn Run As -> Run as Server Sau đó truy cập: http://localhost:8080/data_tranfer/demo


3. Hiển thị dữ liệu mảng

**Cài đặt thư viện JSTL trước khi duyệt mảng

JSTL (JavaServer Pages Standard Tag Library) là thư viện tiêu chuẩn cho JSP, giúp viết code ngắn gọn, dễ đọc khi hiển thị dữ liệu, đặc biệt là lặp (forEach) và điều kiện (if).

Hoặc trực tiếp:

  1. Tải 2 file .jar ở trên.
  2. Copy vào thư mụcsrc/main/webapp/WEB-INF/lib.
  3. Thêm khai báo thư viện trong JSP:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

Trên cùng của file jsp nhúng thư viện JSTL

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<h2>Danh sách trái cây:</h2>
<ul>
<c:forEach var="fruit" items="${fruits}">
    <li>${fruit}</li>
</c:forEach>
</ul>

**Ví dụ 2 hiển thị dữ liệu đối tượng Student: **

** Bước 1: Tạo Class Student **

package entity;

public class Student {
    private int code;
    private String name;
    private String age;
    private String phone;

    public Student() {
        // TODO Auto-generated constructor stub
    }

    public Student(int code, String name, String age, String phone) {
        super();
        this.code = code;
        this.name = name;
        this.age = age;
        this.phone = phone;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

}


** Bước 2: Tạo Servlet, ví dụ đặt tên là StudentServlet Sau đó khai báo code có dạng sau

@WebServlet("/student")
public class StudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        // Truyền dữ liệu cơ bản
        request.setAttribute("msg", "Xin chào từ Servlet!");
        
        // Truyền mảng
        String[] fruits = {"Táo", "Cam", "Chuối"};
        request.setAttribute("fruits", fruits);
        
        // Truyền đối tượng
        Student st = new Student("SV01", "Nguyễn Văn A", 20, "0123456789");
        request.setAttribute("student", st);
        
        // Truyền danh sách đối tượng
        List<Student> list = new ArrayList<>();
        list.add(new Student("SV02", "Trần Thị B", 21, "0987654321"));
        list.add(new Student("SV03", "Lê Văn C", 22, "0911222333"));
        request.setAttribute("students", list);
        
        // Chuyển sang JSP
        request.getRequestDispatcher("/student.jsp").forward(request, response);
    }
}

Bước 3. Hiển thị dữ liệu đối tượng

Trong file src/main/webapp/student.jsp soạn mã tương tự

<h2>Thông tin sinh viên:</h2>
<p>Mã: ${student.code}</p>
<p>Tên: ${student.name}</p>
<p>Tuổi: ${student.age}</p>
<p>SĐT: ${student.phone}</p>

** Hiển thị dữ liệu dạng mảng đối tượng (List<Student>)**

Lưu ý, nhúng thư viện JSTL như bước trên vào đầu file

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<h2>Danh sách sinh viên:</h2>
<table border="1" cellpadding="5">
<tr>
    <th>Mã</th>
    <th>Tên</th>
    <th>Tuổi</th>
    <th>SĐT</th>
</tr>
<c:forEach var="st" items="${students}">
    <tr>
        <td>${st.code}</td>
        <td>${st.name}</td>
        <td>${st.age}</td>
        <td>${st.phone}</td>
    </tr>
</c:forEach>
</table>

Chạy lại dự án, sau đó truy cập: http://localhost:8080/data_tranfer/atudent