1

I am creating a Basic Spring Web application that involves a User logging in and entering their personal dashboard. I have utilised the Default Spring Security Login form when the "login" url is instantiated through the controller. What I would like the know is, how do I retrieve the users personal account information which just logged in from the database? This is what I had in the controller class when the login url had been instantiated

@RequestMapping("dashboard")
public String goDashboard(Model model){
    model.addAttribute("user", new User());
    return "dashboard"; // this is just returning the viewResolver JSP page
}

I am assuming the above is incorrect, as I personally think that making a new Object is wrong and will give me null values. When I login and try to display using:<c:out value="${user.username}" /> Nothing gets displayed.

4

3 回答 3

1

Or you can get it in your controller:

@RequestMapping("dashboard")
public String goDashboard(Model model, Principal principal){
    model.addAttribute("username", principal.getName());
    return "dashboard"; 
}

Such approach will help you keep business logic in controller (separation of concerns).

EDIT. Pass user details object:

@RequestMapping("dashboard")
public String goDashboard(Model model, Principal principal){
    UserDetails userDetails = (UserDetails)((Authentication)principal).getPrincipal()
    model.addAttribute("userDetails", userDetails);
    return "dashboard"; 
}
于 2013-09-12T12:39:51.977 回答
0

if you create new User object, the username will be null definitely (if you have empty default constructor only). You can get username in jsp like this:

<sec:authentication property="principal.username" /> 

and don't forget to add declaration on top:

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

Read more about it here

于 2013-09-12T12:33:59.133 回答
0

You can get it in various ways.

1) Using SecurityContextHolder:

Authentication auth = SecurityContextHolder.getContext().getAuthentication();

and then put it into the model as you do now.

2) Using Spring Security Taglibs:

<sec:authentication property="principal.username" /> // will render name

In this case you do not need to add any code to the controller.

于 2013-09-12T12:35:46.047 回答