为什么我要从另一个控制器中摘录的控制器获得相同的方法?

时间:2019-05-15 09:00:37

标签: spring spring-boot spring-security thymeleaf

我有两个控制器类,RegistrationControllerSuperController用于超级用户。 在RegistrationController中,我有一种注册新用户的方法,在其中,我为新用户指定了某些角色,并将该用户保存在db中。 但是,在第二个控制器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:

<!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/.....

0 个答案:

没有答案