使用springboot+thymeleaf 在html中获取session

Controller

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpSession;

@Controller
public class UserController {

    @GetMapping("/your-page")
    public String yourPage(HttpSession session, Model model) {
        // 获取session中的值
        String loginUserId = (String) session.getAttribute("loginUserId");
        
        // 将值传递给视图
        model.addAttribute("loginUserId", loginUserId);
        
        // 返回视图名称
        return "your-page"; // 这里的 "your-page" 是你的Thymeleaf模板文件的名称
    }
}

html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Your Page</title>
    <!-- 引入jQuery等必要的JavaScript库 -->
</head>
<body>
    <script th:inline="javascript">
        $(document).ready(function() {
            var loginUserId = /*[[${loginUserId}]]*/ '';
            $.ajax({
                url: 'admin/getUser?adminId=' + loginUserId,
                type: 'GET',
                dataType: 'json',
                success: function(data) {
                    // 处理获取的用户数据
                },
                error: function(xhr, status, error) {
                    console.error('Error fetching user data:', error);
                }
            });
        });
    </script>
</body>
</html>
posted @ 2024-04-29 20:23  又一岁荣枯  阅读(131)  评论(0编辑  收藏  举报