Почему я получаю тот же метод от контроллера, исполняемого в другом контроллере? - PullRequest
0 голосов
/ 15 мая 2019

У меня есть два класса контроллеров, RegistrationController и SuperController для суперпользователя.В RegistrationController у меня есть метод регистрации нового пользователя, и в нем я указываю определенные роли для нового пользователя и сохраняю пользователя в БД.Однако во втором контроллере SuperController у меня есть другая конечная точка и другой HTML-файл, который позволяет superUser заполнять информацию о новом пользователе с различными ролями, но я получаю результат метода в RegistrationController

Здесьэто RegistrationController.java:

@Controller
public class RegistrationController {

    @Autowired
    private UserService userService;

    @ModelAttribute("user")
    public UserDto userDto() {
        return new UserDto();
    }

    @RequestMapping(value = "/registration", method = RequestMethod.GET)
    public String showRegistrationForm(Model model) {

        return "registration";
    }


    //Registration
    @RequestMapping(method = RequestMethod.POST)
    public String registerNewUser(@ModelAttribute("user") @Valid  UserDto userDto, BindingResult result ) throws UserAlreadyExistException {

        User exist = userService.findUserByEmail(userDto.getEmail());

        if (exist != null) {
            result.rejectValue("email", null, "There is an account already registered with this email address: ");
            throw new UserAlreadyExistException("There is an account already registered with this email address:  " + userDto.getEmail());
        }

        if (result.hasErrors()){
            return "registration";
        }
        userDto.setCreatedBy("There is an error if this shows in parent");

        exist = userService.registerNewUser(userDto);
        return "redirect:/registration?success";

    }       
}

, и это файл registration.html с thymeleaf:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>

    <link rel="stylesheet" type="text/css" th:href="@{/webjars/bootstrap/3.3.7/css/bootstrap.min.css}"/>
    <link rel="stylesheet" type="text/css" th:href="@{/css/main.css}"/>

    <title>Registration</title>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">

            <div th:if="${param.success}">
                <div class="alert alert-info">
                    You've successfully registered to our awesome app!
                </div>
            </div>

            <h1>Registration</h1>
            <form th:action="@{/registration.html}" th:object="${user}" method="post">

                <p class="error-message"
                   th:if="${#fields.hasGlobalErrors()}"
                   th:each="error : ${#fields.errors('global')}"
                   th:text="${error}">Validation error</p>

                <div class="form-group"
                     th:classappend="${#fields.hasErrors('firstName')}? 'has-error':''">
                    <label for="firstName" class="control-label">First name</label>
                    <input id="firstName"
                           class="form-control"
                           th:field="*{firstName}"/>
                    <p class="error-message"
                       th:each="error: ${#fields.errors('firstName')}"
                       th:text="${error}">Validation error</p>
                </div>
                <div class="form-group"
                     th:classappend="${#fields.hasErrors('lastName')}? 'has-error':''">
                    <label for="lastName" class="control-label">Last name</label>
                    <input id="lastName"
                           class="form-control"
                           th:field="*{lastName}"/>
                    <p class="error-message"
                       th:each="error : ${#fields.errors('lastName')}"
                       th:text="${error}">Validation error</p>
                </div>
                <div class="form-group"
                     th:classappend="${#fields.hasErrors('email')}? 'has-error':''">
                    <label for="email" class="control-label">E-mail</label>
                    <input id="email"
                           class="form-control"
                           th:field="*{email}"/>
                    <p class="error-message"
                       th:each="error : ${#fields.errors('email')}"
                       th:text="${error}">Validation error</p>
                </div>
                <div class="form-group"
                     th:classappend="${#fields.hasErrors('confirmEmail')}? 'has-error':''">
                    <label for="confirmEmail" class="control-label">Confirm e-mail</label>
                    <input id="confirmEmail"
                           class="form-control"
                           th:field="*{confirmEmail}"/>
                    <p class="error-message"
                       th:each="error : ${#fields.errors('confirmEmail')}"
                       th:text="${error}">Validation error</p>
                </div>
                <div class="form-group"
                     th:classappend="${#fields.hasErrors('password')}? 'has-error':''">
                    <label for="password" class="control-label">Password</label>
                    <input id="password"
                           class="form-control"
                           type="password"
                           th:field="*{password}"/>
                    <p class="error-message"
                       th:each="error : ${#fields.errors('password')}"
                       th:text="${error}">Validation error</p>
                </div>
                <div class="form-group"
                     th:classappend="${#fields.hasErrors('confirmPassword')}? 'has-error':''">
                    <label for="confirmPassword" class="control-label">Confirm password</label>
                    <input id="confirmPassword"
                           class="form-control"
                           type="password"
                           th:field="*{confirmPassword}"/>
                    <p class="error-message"
                       th:each="error : ${#fields.errors('confirmPassword')}"
                       th:text="${error}">Validation error</p>

                    <div class="form-group"
                         th:classappend="${#fields.hasErrors('termsAccepted')}? 'has-error':''">
                        <input id="terms"
                               type="checkbox"
                               th:field="*{termsAccepted}"/>
                        <label class="control-label" for="terms">
                            I agree with the <a href="#">terms and conditions</a> for Registration.
                        </label>
                        <p class="error-message"
                           th:each="error : ${#fields.errors('termsAccepted')}"
                           th:text="${error}">Validation error</p>
                    </div>

                </div>

                <div class="form-group">
                    <button type="submit" class="btn btn-success">Register</button>
                    <span>Already registered? <a href="/" th:href="@{/login}">Login here</a></span>
                </div>

            </form>
        </div>
    </div>
</div>


</body>
</html>

Вот SuperController.java

@Controller
@RequestMapping("/user/super")
@Slf4j
public class SuperController {

    @Autowired
    private UserService userService;

    @ModelAttribute("user")
    public UserDto userDto() {
        return new UserDto();
    }    

    @RequestMapping(value = {"/dashboard"}, method = RequestMethod.GET)
    public String showSuperDashBoard(Model model) {

        return "super_dashboard";
    }

    @RequestMapping(value = "/dashboard/add_partner", method = RequestMethod.GET)
    public String showAddPartner(Model model) {

        model.addAttribute("parentEmail", getCurrentUserEmail());
        model.addAttribute("createdByParent", getCurrentUserEmail());
        return "super_add_partner";
    }

    @PostMapping(value = "/dashboard/add_partner")
    public String addNewPartner(@ModelAttribute("user") @Valid UserDto userDto, BindingResult result) throws UserAlreadyExistException {

        log.info("THIS IS PARENT EMAIL VALUE = " + getCurrentUserEmail());

        User existingUser = userService.findUserByEmail(userDto.getEmail());
        if (existingUser != null) {
            result.rejectValue("email", null, "There is an account already registered with this email address:");
            throw new UserAlreadyExistException("There is an account already registered with this email address:" + userDto.getEmail());
        }

        if (result.hasErrors()) {
            return "super_dashboard";
        }

        userDto.setCreatedBy(getCurrentUserEmail() + "Working correctly ");

        userService.registerNewPartner(userDto);
        return "redirect/super_add_partner?success";
    }

    private String getCurrentUserEmail() {

        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userName = userDetails.getUsername();
        return userName;
    }   
}

и super_add_partner.HTML выглядит следующим образом:

<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security"

      layout:decorate="~{fragments/layout}">

<script type="text/javascript" th:src="@{/webjars/jquery/3.2.1/jquery.min.js/}"></script>
<script type="text/javascript" th:src="@{/webjars/bootstrap/3.3.7/js/bootstrap.min.js}"></script>

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div class="container">

    <div th:if="${param.success}">
        <div class="alert alert-info">
            You've successfully added a new partner to our awesome app!
        </div>
    </div>


    <form th:action="@{/super_add_partner.html}" th:object="${user}" method="post">

        <p class="error-message"
           th:if="${#fields.hasGlobalErrors()}"
           th:each="error : ${#fields.errors('global')}"
           th:text="${error}">Validation error</p>

        <div class="form-group"
             th:classappend="${#fields.hasErrors('firstName')}? 'has-error':''">
            <label for="firstName" class="control-label">First name</label>
            <input id="firstName"
                   class="form-control"
                   th:field="*{firstName}"/>
            <p class="error-message"
               th:each="error: ${#fields.errors('firstName')}"
               th:text="${error}">Validation error</p>
        </div>
        <div class="form-group"
             th:classappend="${#fields.hasErrors('lastName')}? 'has-error':''">
            <label for="lastName" class="control-label">Last name</label>
            <input id="lastName"
                   class="form-control"
                   th:field="*{lastName}"/>
            <p class="error-message"
               th:each="error : ${#fields.errors('lastName')}"
               th:text="${error}">Validation error</p>
        </div>
        <div class="form-group"
             th:classappend="${#fields.hasErrors('email')}? 'has-error':''">
            <label for="email" class="control-label">E-mail</label>
            <input id="email"
                   class="form-control"
                   th:field="*{email}"/>
            <p class="error-message"
               th:each="error : ${#fields.errors('email')}"
               th:text="${error}">Validation error</p>
        </div>
        <div class="form-group"
             th:classappend="${#fields.hasErrors('confirmEmail')}? 'has-error':''">
            <label for="confirmEmail" class="control-label">Confirm e-mail</label>
            <input id="confirmEmail"
                   class="form-control"
                   th:field="*{confirmEmail}"/>
            <p class="error-message"
               th:each="error : ${#fields.errors('confirmEmail')}"
               th:text="${error}">Validation error</p>
        </div>
        <div class="form-group"
             th:classappend="${#fields.hasErrors('password')}? 'has-error':''">
            <label for="password" class="control-label">Password</label>
            <input id="password"
                   class="form-control"
                   type="password"
                   th:field="*{password}"/>
            <p class="error-message"
               th:each="error : ${#fields.errors('password')}"
               th:text="${error}">Validation error</p>
        </div>
        <div class="form-group"
             th:classappend="${#fields.hasErrors('confirmPassword')}? 'has-error':''">
            <label for="confirmPassword" class="control-label">Confirm password</label>
            <input id="confirmPassword"
                   class="form-control"
                   type="password"
                   th:field="*{confirmPassword}"/>
            <p class="error-message"
               th:each="error : ${#fields.errors('confirmPassword')}"
               th:text="${error}">Validation error</p>

            <div>
                <h1><span th:text="${parentEmail}">user</span> current user email</h1>

                <input class="form-control"
                       type="text"
                       th:name="parentEmail"
                       th:value="${createdByParent != null} ? ${createdByParent} : ${createdByParent}"
                       th:readonly="${createdByParent=='readonly'}"
                       th:disabled="true"/>

            </div>

            <div class="form-group"
                 th:classappend="${#fields.hasErrors('termsAccepted')}? 'has-error':''">
                <input id="terms"
                       type="checkbox"
                       th:field="*{termsAccepted}"/>
                <label class="control-label" for="terms">
                    I agree with the <a href="#">terms and conditions</a> for Registration.
                </label>
                <p class="error-message"
                   th:each="error : ${#fields.errors('termsAccepted')}"
                   th:text="${error}">Validation error</p>
            </div>    

            <button type="submit" class="btn btn-success">Add new Partner</button>

        </div>


    </form>
</div>
</body>
</html>

Когда я нажимаю добавить нового партнера, я получаю сообщение об успехе, которое определено в registration.html, которое гласит: «Вы успешно зарегистрировались в нашем потрясающем приложении!»вместо правильного сообщения я должен получить из super_add_partner.html, который означает, что вы успешно добавили нового партнера в наше удивительное приложение! "

и в базе данных выглядит, что я добавил нового пользователя после регистрации.

Я что-то упустил?

Результирующие изображения 1st step when filling the form из браузера:

after i click on add partner in the previous form

Вот как выглядит UserServiceImpl:

@Service
public class UserServiceImpl implements UserService {

    //Fields
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private VerificationTokenRepository verificationTokenRepository;
    @Autowired
    private PasswordResetTokenRepository passwordResetTokenRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;    

    //CONST
    public static final String TOKEN_INVALID = "invalidToken";
    public static final String TOKEN_EXPIRED = "expired";
    public static final String TOKEN_VALID = "valid";    

    @Override
    public User registerNewUser(UserDto userDto) throws UserAlreadyExistException {
        if (emailIsExist(userDto.getEmail())) {
            throw new UserAlreadyExistException("There is an account already registered with this email address:" + userDto.getEmail());
        }

        User newUser = new User();

        //b-crypting the password
        String cryptedPassword = passwordEncoder.encode(userDto.getPassword());

        newUser.setFirstName(userDto.getFirstName());
        newUser.setLastName(userDto.getLastName());
        newUser.setEmail(userDto.getEmail());
        newUser.setPassword(cryptedPassword);
        newUser.setCreatedBy(userDto.getEmail());
        newUser.setRoles(Arrays.asList(
                 new Role("ROLE_ADMIN")
                , new Role("ROLE_USER")
        ));

        return userRepository.save(newUser);
    }

    @Override
    public User registerNewPartner(UserDto userDto) throws UserAlreadyExistException {//, Parent parent) throws UserAlreadyExistException {
        if (emailIsExist(userDto.getEmail())) {
            throw new UserAlreadyExistException("There is an account already registered with this email address:" + userDto.getEmail());
        }

        User newUser = new User();
        //b-crypting the password
        String cryptedPassword = passwordEncoder.encode(userDto.getPassword());

        newUser.setFirstName(userDto.getFirstName());
        newUser.setLastName(userDto.getLastName());
        newUser.setEmail(userDto.getEmail());
        newUser.setPassword(cryptedPassword);
        newUser.setCreatedBy(userDto.getCreatedBy());
        newUser.setRoles(Arrays.asList(
                new Role("ROLE_PARTNER")
                , new Role("ROLE_ADMIN")
                , new Role("ROLE_USER")));


        return userRepository.save(newUser);
    }
///rest of the code/.....
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...