Java – obtain the currently logged in user from the spring angle
I use spring security in the spring boot application. I want to get the currently logged in user from the principal #getname, but I have a template parsing error. It contains the user name I want
This is my controller:
import java.security.Principal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class PageController {
@RequestMapping(value = "/api/loggeduser",method = RequestMethod.GET)
public String printWelcome(ModelMap model,Principal principal) {
String name = null;
if (principal !=null) {
name = principal.getName();
}
model.addAttribute("username",name);
return name;
}
}
This is my angularjs function to get the login user:
app.controller('Usercontr',function($scope,$http) {
$http.get("/api/loggeduser").success(function (data) {
$scope.nom = data;
console.log($scope.nom)
})
});
This is an error:
Kamel. Milli is the login user name Can you help me I'm using thymeleaf as the login page, and everything else is HTML angularjs I don't know why Broadway put it on this controller
Solution
Add the @ ResponseBody annotation to the controller:
@ResponseBody
@RequestMapping(value = "/api/loggeduser",method = RequestMethod.GET)
public String printWelcome(ModelMap model,Principal principal ) { ... }
When you use the @ controller stereotype annotation, spring MVC will try to parse your string return value into view, so the error is:
If you only want to write the return value to the response body, you can set the controller to @ restcontroller or annotate a specific controller with @ ResponseBody
This is a bit off topic, but because you are using client view rendering, modelmap is very useless You can get rid of it safely
