Home > Software engineering >  how to send value from thymyleaf to controller which is not used in view
how to send value from thymyleaf to controller which is not used in view

Time:11-04

I am trying to send some value from view to controller however this value is not used in view.

View:

<form th:action="@{/changePassword}" th:object="${user}" method="post">
    <div >
        <label>Old Password</label>
        <input type="text"  th:name="oldPassword">
    </div>
    <div >
        <label>New Password</label>
        <input type="password"  th:name="password">
    </div>
    <div >
        <label>Confirm Password</label>
        <input type="password"  >
    </div>

    <button type="submit" onclick="savePass()">Change Password</button>
</form>

and method in controller

@PostMapping("/changePassword")
    public String updatePassword(@ModelAttribute("user") User user, Model model) {
        model.addAttribute("user", user);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userService.changeUserPassword(user.getUsername(), user.getPassword());
        return "display";
    }

and simple model with id, username, password, oldPassword and enable fields.

I know I can get logged user in view by [[${#httpServletRequest.remoteUser}]] but how can I put it into model and send to controller. With actual code during debugging I can see that password and oldPassword are set but username = null.

I could add:

<div >
       <label>Username</label>
       <input type="text"  th:name="username">
</div>

but I don't want user to type his username, I know who is logged and who wants to change password.

CodePudding user response:

There is no need to send the user from the view to the controller. Just use @AuthenticationPrincipal in your controller:

    @PostMapping("/changePassword")
    public String updatePassword(@AuthenticationPrincipal MySecurityUser securityUser, 
                                 @ModelAttribute("user") User user, 
                                 Model model) {
        model.addAttribute("user", user);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userService.changeUserPassword(user.getUsername(), user.getPassword());
        return "display";
    }

The actual class (MySecurityUser in the example) to use will depend on how exactly you have set up your security. If you don't know it, type it to Object and print out the class name or use a debugger to see the actual class name that is used.

See https://docs.spring.io/spring-security/reference/servlet/integrations/mvc.html#mvc-authentication-principal for more info.

  • Related