Spring Boot中如何通过thymeleaf在两个方法之间传输数据

问题描述 投票:0回答:1

我正在创建一个重置密码页面,其中我有多个页面。在一个页面中,我从用户处获取电子邮件并使用 model.addAttribute() 将该值传递给另一个方法,在 submot 操作显示 null 后,我可以访问控制器中其他方法上的数据;

控制器

@PostMapping("/verify")
    public String forgetPass(Model model,@ModelAttribute("login") Login login){
        if(otpServices.verify(login)){
            String newpass="";
            String email=login.getEmail();
            model.addAttribute("email",email);
            model.addAttribute("pass",newpass);
            return "NewPass";
        }else {
            return "ForgetPass";
        }
    }
    @PostMapping("/newpass")
    public String newPass(@ModelAttribute("email") String email, @ModelAttribute("pass") String pass ){
        userServices.updatePass(email,pass);
        return "Home";
    }

视图(百里叶)

<form th:action="@{/newpass}" method="post" >
                <h2 class="text-center">New Password</h2>
                <div class="alert alert-success text-center" th:text="${email}">
                </div>
                <div class="alert alert-danger text-center">
                </div>
                <div class="form-group">
                    <input class="form-control" type="password" name="password" placeholder="Create new password" required th:field="*{pass}">
                </div>
                <div class="form-group">
                    <input class="form-control" type="password" name="cpassword" placeholder="Confirm your password" required>
                </div>
                <div class="form-group">
                    <input class="form-control button" type="submit" name="change-password" value="Change">
                </div>
            </form>

我还尝试使用对象并将值放入其中,并使用 model.getAttribute 手动访问数据,但每次结果都是 null; 我将不胜感激任何帮助,因为我是新手;

spring spring-boot spring-mvc thymeleaf
1个回答
0
投票

模型属性仅适用于一个请求

你想做的事情是不可能的。模型属性仅在单个请求的生命周期内有效。当 /verify 的发布完成后,所有模型属性都消失了。最后访问它们的地方是 view/Thymeleaf 页面。如果您想在单个请求之外保留状态,您可以将数据放入用户会话中或使用“闪存属性”,它们在幕后执行相同的操作。

设计考虑

我认为你真的应该用一种方法来完成所有这些逻辑。如果验证失败则返回一个响应,如果成功则返回其他内容。使用一种方法来保存电子邮件和密码状态,然后使用另一种方法来实际保存,这似乎是多余的。我建议您将验证放在 /newPass 方法中。

忘记密码大概应该是它自己的方法。 /forgot-password 可以获取电子邮件地址并发送电子邮件令牌。电子邮件中的令牌链接将用户带到一个表单,在其中发布到 /new-password,该方法将验证电子邮件是否唯一,如果不是则保存它。

© www.soinside.com 2019 - 2024. All rights reserved.