Search code examples
angularjsrestspring-bootthymeleaf

How to get userid in angular view from Spring Boot REST Controller


In my application, I am using Spring Security for authentication using database. Part of redirection strategy is to if user is ADMIN, redirect user to ADMIN(HOME) page, if user is USER, redirect that user to USER page.

When a user with role USER logs in, he sees USER page which is like below:

<html ng-app="benefitApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Benefit Application</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="/css/bootstrap.css" />
<script src="https://code.angularjs.org/1.6.1/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-route.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-resource.js"></script>
<script type="text/javascript" src="./js/app.js"></script>
</head>
<body ng-controller="UserCtrl">
<p>Hello <p th:text="${name}"></p></p>
<div>
    <ul class="menu">        
        <li><a href='userProfile({{userid}})'>userprofile</a></li>                
    </ul>
    <div ng-view="ng-view"></div>
</div>
</body>
</html>

I am trying to pass logged in user's id to this page from REST controller like this :

@RequestMapping(value = "/user", method = RequestMethod.GET)
public String userpage(Model model) {
    LOGGER.info(" Enter >> userpage() ");
    Authentication auth = SecurityContextHolder.getContext()
        .getAuthentication();
    String name = auth.getName();
    User user = userManager.findUserByEmail(name);
    model.addAttribute("name", name);
    model.addAttribute("userid", user.getId());
    return "user";
}

But I am not getting any userid in user.html page. What am I missing here?


Solution

  • You are using angularjs data-binding expression to bind userid to function:

    <li><a href='userProfile({{userid}})'>userprofile</a></li> 
    

    which is wrong way.

    Since you are using Thymeleaf, I would suggest you to use expression like this to bind link for user profile : th:href="@{${link}}"

    @ prefix is used to specify a link and $ prefix is used to bind your model value and then create a link with th:href like this:

    <li><a th:href="@{'#/user/profile/' + ${userid}}">userprofile</a></li> 
    

    Or you can initialize a variable with ng-init like this:

    <div ng-init="userId = ${userid}"></div>
    

    And use it like this:

    <li><a ng-href="#/user/profile/{{userId}}">userprofile</a></li>