Java Spring Boot: Проблема с нулевым значением атрибута модели - PullRequest
0 голосов
/ 14 июля 2020

Я разрабатываю Java Spring Boot Web App и в настоящее время пытаюсь реализовать «Забыли пароль?» характерная черта. В рамках этой функции пользователь нажимает «Забыли пароль?» ссылка, по которой они забывают пароль. jsp. Там пользователь должен ввести свой адрес электронной почты для приложения, чтобы затем на его учетную запись электронной почты можно было отправить письмо с подтверждением, а затем они могли щелкнуть ссылку в электронном письме, чтобы затем создать новый пароль. Когда они нажимают ссылку в письме, они перенаправляются на resetPassword. jsp. Я хочу, чтобы на этой странице было два поля: одно с автоматическим заполнением только для чтения, показывающее адрес электронной почты пользователя, и следующее поле ввода, которое позволит пользователю ввести свой новый пароль.

Моя проблема, однако, в том, что я по какой-то причине в настоящее время не могу использовать адрес электронной почты, указанный в файле ForgotPassword. jsp, в resetPassword. jsp. Прямо сейчас он говорит, что в методе контроллера resetPassword (), показанном ниже, user.getEmail () имеет значение null, и поэтому я не могу предоставить новый пароль для текущей учетной записи. Я вставил ниже страницы ForgotPassword. jsp, resetPassword. jsp, а также соответствующие методы контроллера. У меня должно быть что-то не так с параметрами метода контроллера и / или атрибутами модели в resetPassword (), но я не уверен, где именно. Любая помощь будет принята с благодарностью.

ForgotPassword. jsp

<div id="editAccount">

    <div class="row parentRow">

        <div class="parentCol">

            <div class="panel panel-default"
                style="flex-direction: row; min-width: 60%;">

                <div style="text-align: center;">
                    <div
                        style="padding-top: 15%; font-size: x-large; color: black; padding-bottom: 3%;">Reset Password</div>
                </div>

                <div style="flex-grow: 1;">

                    <form:form modelAttribute="user">

                        <%-- <div class="errors">
                            <form:errors path="plainPassword" />
                        </div> --%>

                        <div class="input-group">
                            <form:input type="text" name="email" path="email"
                                placeholder="Email Address"
                                style="margin-top: 8%; min-width: 100%;" />
                        </div>

                        <div style="margin-top: 8%; text-align: center; min-width: 100%;">
                        
                            <input type="submit" name="submit" value="Reset"
                                class="suit_and_tie" /> 
                            <input type="reset" name="clear"
                                value="Clear" class="suit_and_tie" />
                                
                        </div>

                    </form:form>

                </div>

            </div>

        </div>

    </div>
    
</div>

resetPassword. jsp

<div id="editAccount">

    <div class="row parentRow">

        <div class="parentCol">

            <div class="panel panel-default"
                style="flex-direction: row; min-width: 60%;">

                <div style="text-align: center;">
                    <div
                        style="padding-top: 15%; font-size: x-large; color: black; padding-bottom: 3%;">Enter New Password</div>
                </div>

                <div style="flex-grow: 1;">

                    <form:form modelAttribute="user">

                        <div class="errors">
                            <form:errors path="plainPassword" />
                        </div>
                        
                        <div class="input-group">
                            <form:input type="text" name="email" path="email"
                                value="${user.email}" readonly
                                style="margin-top: 8%; min-width: 100%;" />
                        </div>

                        <div class="input-group">
                            <form:input type="password" name="newPassword" path="plainPassword"
                                placeholder="New Password"
                                style="margin-top: 8%; min-width: 100%;" />
                        </div>

                        <div style="margin-top: 8%; text-align: center; min-width: 100%;">
                        
                            <input type="submit" name="submit" value="Submit"
                                class="suit_and_tie" /> 
                            <input type="reset" name="clear"
                                value="Clear" class="suit_and_tie" />
                                
                        </div>

                    </form:form>

                </div>

            </div>

        </div>

    </div>

</div>

controller

    // Display the form
    @RequestMapping(value="/forgotPassword", method=RequestMethod.GET)
    public ModelAndView displayResetPassword(ModelAndView modelAndView, @ModelAttribute("user") SiteUser user) {
        modelAndView.getModel().put("user", user);
        modelAndView.setViewName("app.forgotPassword");
        return modelAndView;
    }

    // Receive the address and send an email
    @RequestMapping(value="/forgotPassword", method=RequestMethod.POST)
    public ModelAndView forgotUserPassword(ModelAndView modelAndView, @Valid SiteUser user, BindingResult result) {
        SiteUser existingUser = userRepo.findByEmail(user.getEmail());
        if (existingUser != null) {
            
            String token = userService.createEmailVerificationTokenForgotPassword(existingUser).toString();

            emailService.sendVerificationEmailForgotPassword(user.getEmail(), token);
            modelAndView.setViewName("redirect:/verifyEmail");

        } else {
            modelAndView.setViewName("redirect:/invalidUser");
        }
        return modelAndView;
    }
    
    @RequestMapping(value="/resetPassword", method= {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView resetPassword(ModelAndView modelAndView, @ModelAttribute(value="user") @Valid SiteUser user, BindingResult result) {
        
        modelAndView.getModel().put("user", user);
        
        System.out.println(user.getEmail());
        
        if (user.getEmail() != null)
        {
            SiteUser tokenUser = userRepo.findByEmail(user.getEmail());
            tokenUser.setPlainPassword((user.getPassword()));
            userRepo.save(tokenUser);
            modelAndView.setViewName("redirect:/passwordReset");
        } 
        
        else {
            modelAndView.setViewName("redirect:/invalidLink");
        }
        
        return modelAndView;
    }
    
    
    @RequestMapping(value="/confirmReset", method= {RequestMethod.GET, RequestMethod.POST})
    ModelAndView confirmReset(ModelAndView modelAndView, @RequestParam("t") String tokenString, BindingResult result) {
        
        ForgotPasswordToken token = userService.getForgotPasswordToken(tokenString);
        
        if(token == null) {
            modelAndView.setViewName("redirect:/invalidUser");
            userService.deleteToken(token);
            return modelAndView;
        }
        
        Date expiryDate = token.getExpiryDate();
        
        if(expiryDate.before(new Date())) {
            modelAndView.setViewName("redirect:/expiredToken");
            userService.deleteToken(token);
            return modelAndView;
        }
        
        SiteUser user = token.getUser();
        
        if (user == null) {
            modelAndView.setViewName("redirect:/invalidUser");
            userService.deleteToken(token);
            return modelAndView;
        }
        
        userService.deleteToken(token);
        user.setEnabled(true);
        userService.save(user);
        
        modelAndView.setViewName("redirect:/resetPassword");
        return modelAndView;
    }
...