Truyền Dữ Liệu Phản Hồi Trong Spring MVC

1. Sử dụng Model để truyền dữ liệu

Model là một class hệ thống trong Spring MVC, hoạt động dựa trên cấu trúc Map để lưu trữ và truyền tải dữ liệu giữa controller và view.

Giao diện JSP đầu vào

<form action="/annotation/XuLyDuLieu" method="post">
    Thông tin tài khoản:
Tên đăng nhập: <input type="text" name="ten">
Mật khẩu: <input type="text" name="matKhau">
Thông tin cá nhân:
Họ tên: <input type="text" name="nguoiDung.ten">
Tuổi: <input type="text" name="nguoiDung.tuoi">
Ngày sinh (yyyy-mm-dd): <input type="text" name="nguoiDung.ngaySinh">
<input type="submit" value="Gửi dữ liệu"> </form>

Controller xử lý

@Controller
@RequestMapping("/duLieu")
public class XuLyDuLieuController {
    
    @RequestMapping(path = "/XuLy", method = RequestMethod.POST)
    public String xuLyDuLieu(Model model, TaiKhoan taiKhoan) {
        model.addAttribute("taiKhoan", taiKhoan);
        return "hienThi";
    }
}

View kết quả (hienThi.jsp)

<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" %>
<html>
<head><title>Kết quả</title></head>
<body>
    <p>Tên đăng nhập: ${taiKhoan.ten}</p>
    <p>Mật khẩu: ${taiKhoan.matKhau}</p>
    <p>Họ tên người dùng: ${taiKhoan.nguoiDung.ten}</p>
    <p>Tuổi người dùng: ${taiKhoan.nguoiDung.tuoi}</p>
    <p>Ngày sinh: ${taiKhoan.nguoiDung.ngaySinh}</p>
</body>
</html>

2. Quản lý session với @SessionAttributes

Spring MVC cung cấp annotation @SessionAttributes để duy trì dữ liệu qua nhiều request.

Controller với session attributes

@SessionAttributes(value = {"taiKhoan"}, types = {TaiKhoan.class})
@Controller
@RequestMapping("/session")
public class SessionController {
    
    @ModelAttribute
    public TaiKhoan taoDuLieuMau() {
        NguoiDung nguoiDung = new NguoiDung();
        nguoiDung.setTen("Nguyen Van A");
        nguoiDung.setTuoi(25);
        
        TaiKhoan taiKhoan = new TaiKhoan();
        taiKhoan.setNguoiDung(nguoiDung);
        return taiKhoan;
    }

    @RequestMapping("/luu")
    public String luuDuLieu(Model model, TaiKhoan taiKhoan) {
        model.addAttribute("taiKhoan", taiKhoan);
        return "hienThiSession";
    }

    @RequestMapping("/doc")
    public String docDuLieu(ModelMap model) {
        System.out.println("Giá trị session: " + model.get("taiKhoan"));
        return "hienThiSession";
    }

    @RequestMapping("/xoa")
    public String xoaSession(SessionStatus status) {
        status.setComplete();
        return "hienThiSession";
    }
}

View hiển thị session (hienThiSession.jsp)

<p>Request scope: ${requestScope.taiKhoan.ten}</p>
<p>Session scope: ${sessionScope.taiKhoan.nguoiDung.ten}</p>

3. Cơ chế hoạt động

  • @SessionAttributes giữ dữ liệu tồn tại trong session thay vì chỉ một request
  • SessionStatus.setComplete() dùng để xóa dữ liệu session
  • ModelAttribute cho phép chuẩn bị dữ liệu trước khi xử lý request

Thẻ: spring-mvc sessionattributes model jsp-el web-development

Đăng vào ngày 22 tháng 5 lúc 02:15