bisorniyesordum
bisorniyesordum

Reputation: 119

How can I save information for current user in Spring & Hibernate?

I have a User table and a UserInfo table which keeps the personal information of the user. What I am trying to do is adding personel information after log in. There is OneToOne relationship between tables with userId column so I defined it like this :

UserInfo class :

public class UserInfo {

//...

@OneToOne
@JoinColumn(name="user_id")
private User user;
// ...
}

User class :

 public class User implements UserDetails {
// ...

 @OneToOne(mappedBy="user", cascade = CascadeType.ALL, fetch=FetchType.LAZY,optional=true)
 private UserInfo userInfo;

 ...
}

After I log in, I want to add some user information to the db for current user. But I don't know how can i save user information in controller? Should I save User object like below? I've searched about it and there is a way to get current user's information:

(User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

But when I try to use it in the controller it just returns null. How can I do such operations (adding pers. info) for logged in user?

@RequestMapping(value = "/show", method = RequestMethod.POST)
public ModelAndView newUser(ModelMap model, Principal principal) {


    ModelAndView result = new ModelAndView("home");

    User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();


    UserInfo userinfo = new UserInfo();

    userinfo.setPlacesVisit(userinfo.getPlacesVisit());
    user.setUserInfo(userinfo);

    userService.save(user);

    String message = "Userinfo was successfully added.";
    result.addObject("message", message);

    return result;

}

Upvotes: 1

Views: 5415

Answers (4)

subhash lamba
subhash lamba

Reputation: 216

instead of saving current object update current object. First get current user object in controller after that set UserInfo then update user object in database.

 @RequestMapping(value = "/show", method = RequestMethod.POST)
    public ModelAndView newUser(ModelMap model, Principal principal) {
        String userName=principal.getName(); // username or email using user login
        User user=userService.getUserByName(userName); // retrieve current user information
        UserInfo userinfo = new UserInfo();  // create userinfor object
        userinfo.setPlacesVisit(userinfo.getPlacesVisit());
            user.setUserInfo(userinfo);   // set userinfo to user
        userService.update(user);  // update user
         String message = "Userinfo was successfully added.";
             result.addObject("message", message);
        return result;

    }

Upvotes: 1

herau
herau

Reputation: 1516

You can retrieve to user with the Principal parameter :

public ModelAndView newUser(ModelMap model, Principal principal) {

  User activeUser = (User) ((Authentication) principal).getPrincipal();

}

SecurityContextHolder is a part of Spring Security. If you want to use this component, you have to set up Spring Security for the log in of your application to be able to retrieve, in your REST controller, the current user (javax.security.Principal)

Spring Security Documentation

Upvotes: 1

annaskulimowska
annaskulimowska

Reputation: 61

You can save your logged user in session:

FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
request.getSession().setAttribute("key", user);

and if you want get currently logged user, just:

(User) user = ((HttpServletRequest) request).getSession().getAttribute("key")

This example is in JSF, but I am sure that is also possible without JSF

Upvotes: 0

Florescent Ticker
Florescent Ticker

Reputation: 645

You can use session to save session attributes. In spring, you can access session using

ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
           HttpSession session = attr.getRequest().getSession();

Upvotes: 0

Related Questions