亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何注入用戶名(不是身份驗證)?

如何注入用戶名(不是身份驗證)?

忽然笑 2021-09-03 13:53:33
在我的 spring boot 應用程序中,在我的 rest 控制器中,我成功地注入了一個實例Authentication來獲取會話的用戶信息。但是,在所有這些控制器中,我目前調用這樣的輔助方法:@GetMappingpublic List<String> getData(Authentication auth) {    String username = auth.getName().replaceFirst(".*?\\\\", ""); // to remove windows domain name    // the rest of these methods only use variable `username`, never `auth`}如何減少此代碼重復?
查看完整描述

1 回答

?
GCT1015

TA貢獻1827條經驗 獲得超4個贊

您可以按如下方式創建一個實用程序類,然后您可以UserUtility.getUsername()在任何需要的地方使用它。


public class UserUtility {


    public static String getUsername(){

        if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null) {

            return SecurityContextHolder.getContext().getAuthentication().getPrincipal());

        }

        return null;

    }

}


查看完整回答
反對 回復 2021-09-03
  • 1 回答
  • 0 關注
  • 182 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號