Search code examples
javaauthenticationservletsjakarta-ee

How does getUserPrincipal() work? When should i use it?


I'm kinda new to Java EE and trying to learn it. So it's unclear to me how exactly request.getUserPrincipal() works. Where it gets Principal object? When and how this object is created?

So let's assume I have a login form that passes user name and password in HTTP POST request. In my servlet I have to take this data and compare it to records in my database. If find one, create user object with his name and some other data. In this case, when do I need to call getUserPrincipal()? And do i really need to call it, because there's already some logic which return a user object? And how this method will get Principal object for me?


Solution

  • request.getUserPrincipal() will be populated when you use container managed authentication. Since you have implemented your own authentication that method will return null and can be safely ignored.