从get到post方法传递参数

时间:2018-03-21 08:15:25

标签: spring spring-mvc spring-boot

我正在构建一个用户可以重置密码的网站功能。他收到一封电子邮件,其中包含生成的令牌。单击此链接后,用户将被发送到/ reset页面。该页面的Get方法如下:

 @RequestMapping(value = "/reset", method = RequestMethod.GET)
public ModelAndView displayResetPasswordPage(ModelAndView modelAndView, @ModelAttribute User user, @RequestParam("token") String token) {

    User u = userService.findByResetToken(token);


    if (u == null) {
        modelAndView.setViewName("error/404");
        return modelAndView;
    } else {
        modelAndView.addObject("token", token);
        modelAndView.setViewName("resetPassword");
        return modelAndView;
    }
}

这样可以正常工作,如果更改了网址中的令牌,则会将用户发送到错误页面。现在我想传递这个"令牌" post方法的参数:

 @RequestMapping(value = "/reset", method = RequestMethod.POST)
public ModelAndView setNewPassword(ModelAndView modelAndView, @RequestParam Map<String, String> requestParams, @ModelAttribute User user, BindingResult bindingResult,  RedirectAttributes redir) {

    System.out.println("token: " + requestParams.get("token"));
    User u = userService.findByResetToken(requestParams.get("token"));

 //   User u = userService.findByEmail(user.getEmail());       


    if (u != null) {

        User updatedUser = userService.updateUserPassword(user);

        modelAndView.addObject("User",updatedUser);
        modelAndView.setViewName("redirect:login");
        return modelAndView;

    } else {
        modelAndView.setViewName("resetPassword");
    }

    return modelAndView;
}

这总是返回resetPassword视图,因为requestparams.get(&#34; token&#34;)总是返回一个空字符串。我没有使用正确的方法来获得参数值吗?

重置密码视图:

<div class="wrapper">
<form class="form-signin" th:action="@{/reset}" method="post" th:object="${user}">
    <h2 class="form-signin-heading">Reset wachtwoord</h2>
    <input type="hidden" name="token" th:value="*{resetToken}"/>       
    <div class="form-group">
        <input type="password" th:field="*{encryptedPassword}" id="password" class="form-control input-lg"
               placeholder="Password" tabindex="3"/>

    <div class="form-group">
        <input type="password" th:field="*{matchingPassword}" id="password_confirmation"
               class="form-control input-lg" placeholder="Confirm Password" tabindex="4"/>
    </div>

    <div class="row">
        <div class="col-xs-6 col-sm-6 col-md-6">
            <input type="submit" class="btn btn-secondary" value="Registreer"/>
        </div>
    </div>
</form>

1 个答案:

答案 0 :(得分:0)

这可以通过使用允许您的令牌在Flash Scope中存活的redirect来完成。你可以通过以下方式做到:

  1. 使第一个控制器方法通过redirect
  2. 访问第二个控制器方法
  3. 在您的第一个控制器方法上使用RedirectAttributes并明确将您的令牌添加到RedirectAttributes Flash Attribute
  4. Take a look at the documentation about RedirectAttributes

相关问题