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

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

springboot普通類中如何獲取session?

springboot普通類中如何獲取session?

滄海一幻覺 2019-02-16 21:44:20
在springboot項目中有一個消息處理類,要在其中獲取到httpSession,用@Autowired獲取不到。 public class TMessageHandlerFactory implements MessageHandlerFactory { @Autowired private HttpSession session; @Override public void data(InputStream data) { int userId = (int)session.getAtrribute("key"); //這里的session為空 .... //插入數據 } } 如果用構造函數傳過來也不行。 @Component public class SMTPRunner implements ApplicationRunner { @Autowired private UserService userService; //不明白為什么這個可以獲取到 @Autowired private HttpSession session; //這個卻不行 @Override public void run(ApplicationArguments applicationArguments) throws Exception { TMessageHandlerFactory myFactory = new TMessageHandlerFactory(session); .... } } 即使使用SpringBeanFacotryUtil (implements ApplicationContextAware) 也不行。 @Component public class SpringBeanFactoryUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if(SpringBeanFactoryUtil.applicationContext == null) { SpringBeanFactoryUtil.applicationContext = applicationContext; } } //獲取applicationContext public static ApplicationContext getApplicationContext() { return applicationContext; } //通過name獲取 Bean. public static Object getBean(String name){ return getApplicationContext().getBean(name); } //通過class獲取Bean. public static <T> T getBean(Class<T> clazz){ return getApplicationContext().getBean(clazz); } //通過name,以及Clazz返回指定的Bean public static <T> T getBean(String name,Class<T> clazz){ return getApplicationContext().getBean(name, clazz); } } 這種方法只能獲取到自定義的bean(UserService這種),獲取不到HttpSession這種Bean。應該如何做呢?可以給個比較詳細的代碼嗎?網上的資料試了都不太行。
查看完整描述

2 回答

?
紅糖糍粑

TA貢獻1815條經驗 獲得超6個贊

//獲取到當前線程綁定的請求對象
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
//已經拿到session,就可以拿到session中保存的用戶信息了。
System.out.println(request.getSession().getAttribute("userInfo"));

我猜樓主你是需要這個

查看完整回答
反對 回復 2019-03-01
?
梵蒂岡之花

TA貢獻1900條經驗 獲得超5個贊

我發現其實不應該這樣做,與session有關的操作,應該放在能獲取到session的上下文中(如Controller中),而不應該放在一個單獨的線程中,大概是因為項目的線程和context無關,所以線程中無法獲取session。正確的做法應該是把和session有關的操作放到Controller中(或其他含有context的環境),再轉移到線程進行處理。

查看完整回答
反對 回復 2019-03-01
  • 2 回答
  • 0 關注
  • 1505 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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