生活随笔
收集整理的這篇文章主要介紹了
如何在Play Framework 2中实现会话超时
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
如果您遵循Play Framework 2指南以實施身份驗證: http://www.playframework.com/doc-m-e-t-t-i o / n..2..2..2 / Jac agéide4-您會注意到Play框架2中沒有會話超時。在Play框架1中存在,但Play框架2采用了不同的方法。
我要實現自己的會話超時,然后通過擴展Security.Authenticator遵循設置身份驗證的指南 ,并在會話中存儲時間戳,并在每次發出請求時繼續擴展它。
這是我的做法:
public class Secured extends Security.Authenticator {public static final String UNAUTHENTICATED = "unauthenticated";public static User getLoggedInUser() {if (session("userId") == null)return null;return User.findById(Long.parseLong(session("userId")));}public static String getLoggedInUsername() {if (session("userId") == null)return null;return User.findById(Long.parseLong(session("userId"))).getUsername();}@Overridepublic String getUsername(Http.Context ctx) {// see if user is logged inif (session("userId") == null)return null;// see if the session is expiredString previousTick = session("userTime");if (previousTick != null && !previousTick.equals("")) {long previousT = Long.valueOf(previousTick);long currentT = new Date().getTime();long timeout = Long.valueOf(Play.application().configuration().getString("sessionTimeout")) * 1000 * 60;if ((currentT - previousT) > timeout) {// session expiredsession().clear();return null;}}// update time in sessionString tickString = Long.toString(new Date().getTime());session("userTime", tickString);return User.findById(Long.parseLong(session("userId"))).getUsername();}
}
然后只需將sessionTimeout=15 (以分鐘為單位)添加到您的conf文件中。
翻譯自: https://www.javacodegeeks.com/2014/04/how-to-implement-a-session-timeout-in-play-framework-2.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
以上是生活随笔為你收集整理的如何在Play Framework 2中实现会话超时的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。