Shiro學習:記一次model在重定向後的數據丟失

@RequestMapping("/user/hello")
    public String hello(Model model) {
        model.addAttribute("hello","world");
        model.addAttribute("hello2","world");
        return "test";
    }
    /**
     * 測試thymeleaf
     *
     */
    @RequestMapping("/testThymeleaf")
    public String TestThymeleaf(Model model){
        model.addAttribute("username","asdasdas");
        return "redirect:/user/hello";
    }

對於以上代碼,在開發過程中我們可以會遇到很多次,比如在驗證後添加提示信息,然後轉到登錄頁面等。今天在整理Shiro的時候,遇到了model數據丟失的情況,就是在重定向後model的數據被清空了?以前一直沒有遇到,這裏遇到了,就記錄一下。

<!DOCTYPE html>


<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>測試</title>
</head>
<body>
<h3 th:text="${username}"></h3>
進入用戶添加功能:<a href="add">用戶添加</a>
進入用戶更新功能:<a href="update">用戶更新</a>

</body>
</html>

預想的結果是:會有一個h3的字符串會顯示出來。

但是實際結果:

在這裏插入圖片描述
我們發現,並沒有這個字符串,這是爲什麼呢?
後來debug調試發現,在使用redirect重定向請求後,model的值被清空了,所以造成了model數據丟失的情況。

怎麼解決?

@RequestMapping("/login")
    public String login(User user, RedirectAttributesModelMap model){
        System.out.println(user.toString());
        /**
         * 使用shiro編寫認證操作
         */
        //1、獲取Subject
        Subject subject= SecurityUtils.getSubject();

        //2、封裝用戶數據
        UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(),user.getPassword());

        //3、執行登陸方法
        try {
            subject.login(token); // ===>去到ShiroConfig的驗證操作
            //登陸成功
            model.addFlashAttribute("msg","登陸成功");
            System.out.println("登陸成功");
            return "redirect:testThymeleaf";
        }catch (UnknownAccountException e){
            //登陸失敗:用戶名不存在
            model.addFlashAttribute("msg","用戶名不存在");
            System.out.println("用戶名不存在");
            return "redirect:/to_login";
        }catch (IncorrectCredentialsException e){
            //登陸失敗:密碼錯誤
            model.addFlashAttribute("msg","密碼錯誤");
            System.out.println("密碼錯誤");
            return "redirect:/to_login";
        }
    }

我們只需要把Model改爲RedirectAttributesModelMap 就可以了,這樣在重定向後不會丟失model的數據。
在這裏插入圖片描述
在這裏插入圖片描述

這樣就達到了預期的效果了.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章