Request parameter with thymeleaf

2020-07-23 05:24发布

问题:

In a Spring Boot web app, User wants to reset his password, so he enters Reset password page. Now I want to let him type his email address, push Reset and I want to redirect to myapp/resetPassword?email=HIS_EMAIL to handle password reset.

MY code:

@RequestMapping(value = "/resetPassword", method = RequestMethod.GET)
public String resetPasswordForm(Model model){
    model.addAttribute("email", new String());
    return "resetPassword";
}

@RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
public String resetPassword(@RequestParam("email") String email) {
    User user = userService.findUserByEmail(email);
    //playing with logic
    return "redirect:/";
}

How can I achieve it on my thymeleaf page? I tried something like this:

<form th:action="@{/resetPassword(email=${email})}" method="post">
    <input type="email" th:field="${email}" th:placeholder="Email" />
        <div class="clearfix">
            <button type="submit">Reset</button>
        </div>
</form>

Unfortunately my email is always null. Can somebody help?

回答1:

"th:field" is for Entity-Beans only. This should work:

@GetMapping(value = "/resetPassword")
public String resetPassword(@RequestParam(value="email",required=false) String email) {
    if(email==null)
        return "resetPassword";
    User user = userService.findUserByEmail(email);
    //playing with logic
    return "redirect:/";     
}

<form th:action="@{/resetPassword}" method="get">
    <input type="email" th:name="email" th:placeholder="Email" />
    <div class="clearfix">
        <button type="submit">Reset</button>
    </div>
</form>

And don't forget: Thymeleaf is not Javascript. It is rendered on Server. Thinks like @{/resetPassword(email=${email})} would output e.g. /resetPassword?email=anValueYouAddedToModelInController