HttpServletRequest.getRemoteUser() vs HttpServletRequest.getUserPrincipal().getName()

前端 未结 3 1180
隐瞒了意图╮
隐瞒了意图╮ 2021-01-31 16:44

These two seem to be doing the same things. Can anyone explain the main difference between the two? When would you use one vs the other?

HttpServletRequest.getRemoteU

3条回答
  •  清歌不尽
    2021-01-31 17:47

    The getUserPrincipal() method returns an object of some class derived from the Principal interface, which is an abstraction of the entity that is the "user" responsible for the request. From it you get an actual object that, depending on the implementing class, you can use to get all sorts of information about that user/identity. One of those properties is the string-representation of the name of the user/identity, which you obtain by calling getName().

    getRemoteUser() is really just a shortcut to getting that string-representation. You don't have access to any other methods implemented by the implementing class, not do you have access to the object itself, just the string-representation of the name.

    For most use-cases that I am familiar with, that string-representation is what you want; I believe this is why getRemoteUser() exists - it's a common case so there's an easy/quick way to get access to it without actually getting a reference to an implementing class object.

提交回复
热议问题