1

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;

}
bisorniyesordum
  • 119
  • 1
  • 3
  • 8

4 Answers4

1

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

herau
  • 1,466
  • 2
  • 18
  • 36
  • I'm trying to use Principal param. but it gives this error for that line: **java.lang.ClassCastException: java.lang.String cannot be cast to org.temp.model.User** and kind of a file downloading pop-up appears I don't know what it is. Did u checked my controller is the rest is true? I mean declerations and those kind of stuff. – bisorniyesordum Apr 19 '14 at 13:19
  • Your rest controller is setting to POST. is it normal ? maybe you can try this [solution](http://stackoverflow.com/questions/8764545/best-practice-for-getting-active-users-userdetails) – herau Apr 19 '14 at 15:00
1

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;

    }
subhash lamba
  • 216
  • 1
  • 14
  • I solved this but, now the problem is whenever I update the profile it inserts a new column to userinfo table. For example if I update my profile info for 5 times when everytime it saves these, it cerates a new row. How can I keep just one row for related user? – bisorniyesordum May 01 '14 at 20:03
  • in hibernate use sessionFactory.getCurrentSession().update(object) to update Object. – subhash lamba May 02 '14 at 08:18
0

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();
0

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