com.blade.mvc.http.Session Java Examples

The following examples show how to use com.blade.mvc.http.Session. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: App.java    From tutorials with MIT License 6 votes vote down vote up
public static void main(String[] args) {

        Blade.of()
            .get("/", ctx -> ctx.render("index.html"))
            .get("/basic-route-example", ctx -> ctx.text("GET called"))
            .post("/basic-route-example", ctx -> ctx.text("POST called"))
            .put("/basic-route-example", ctx -> ctx.text("PUT called"))
            .delete("/basic-route-example", ctx -> ctx.text("DELETE called"))
            .addStatics("/custom-static")
            // .showFileList(true)
            .enableCors(true)
            .before("/user/*", ctx -> log.info("[NarrowedHook] Before '/user/*', URL called: " + ctx.uri()))
            .on(EventType.SERVER_STARTED, e -> {
                String version = WebContext.blade()
                    .env("app.version")
                    .orElse("N/D");
                log.info("[Event::serverStarted] Loading 'app.version' from configuration, value: " + version);
            })
            .on(EventType.SESSION_CREATED, e -> {
                Session session = (Session) e.attribute("session");
                session.attribute("mySessionValue", "Baeldung");
            })
            .use(new BaeldungMiddleware())
            .start(App.class, args);
    }
 
Example #2
Source File: TaleUtils.java    From tale with MIT License 5 votes vote down vote up
/**
 * 返回当前登录用户
 *
 * @return
 */
public static Users getLoginUser() {
    Session session = com.blade.mvc.WebContext.request().session();
    if (null == session) {
        return null;
    }
    Users user = session.attribute(TaleConst.LOGIN_SESSION_KEY);
    return user;
}
 
Example #3
Source File: SessionHandler.java    From blade with Apache License 2.0 5 votes vote down vote up
private Session getSession(Request request) {
    String cookieHeader = request.cookie(WebContext.sessionKey());
    if (StringKit.isEmpty(cookieHeader)) {
        return null;
    }
    return sessionManager.getSession(cookieHeader);
}
 
Example #4
Source File: SessionManager.java    From blade with Apache License 2.0 5 votes vote down vote up
/**
 * Add a session instance to sessionMap
 *
 * @param session session instance
 */
public void createSession(Session session) {
    sessionMap.put(session.id(), session);
    Event event = new Event();
    event.attribute("session", session);

    eventManager.fireEvent(EventType.SESSION_CREATED, event);
}
 
Example #5
Source File: SessionManager.java    From blade with Apache License 2.0 5 votes vote down vote up
/**
 * Remove a session
 *
 * @param session session instance
 */
public void destorySession(Session session) {
    session.attributes().clear();
    sessionMap.remove(session.id());

    Event event = new Event();
    event.attribute("session", session);

    eventManager.fireEvent(EventType.SESSION_DESTROY, event);
}
 
Example #6
Source File: SessionCleaner.java    From blade with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    try {
        Collection<Session> sessions = sessionManager.sessionMap().values();
        sessions.parallelStream().filter(this::expires).forEach(sessionManager::destorySession);
    } catch (Exception e) {
        log.error("Session clean error", e);
    }
}
 
Example #7
Source File: AttributesExampleController.java    From tutorials with MIT License 5 votes vote down vote up
@GetRoute("/session-attribute-example")
public void getSessionAttribute(Request request, Response response) {
    Session session = request.session();
    session.attribute("session-val", SESSION_VALUE);
    String sessionVal = session.attribute("session-val");
    response.text(sessionVal);
}
 
Example #8
Source File: AuthController.java    From tale with MIT License 4 votes vote down vote up
@Route(value = "login", method = HttpMethod.POST)
@JSON
public RestResponse doLogin(LoginParam loginParam, Request request,
                            Session session, Response response) {

    Integer error_count = cache.get("login_error_count");
    try {
        error_count = null == error_count ? 0 : error_count;
        if (null != error_count && error_count > 3) {
            return RestResponse.fail("您输入密码已经错误超过3次,请10分钟后尝试");
        }

        long count = new Users().where("username", loginParam.getUsername()).count();
        if (count < 1) {
            return RestResponse.fail("不存在该用户");
        }
        String pwd = EncryptKit.md5(loginParam.getUsername(), loginParam.getPassword());

        Users user = new Users().where("username", loginParam.getUsername()).and("password", pwd).find();
        if (null == user) {
            return RestResponse.fail("用户名或密码错误");
        }
        session.attribute(TaleConst.LOGIN_SESSION_KEY, user);
        if (StringKit.isNotBlank(loginParam.getRemeberMe())) {
            TaleUtils.setCookie(response, user.getUid());
        }

        Users temp = new Users();
        temp.setLogged(DateKit.nowUnix());
        temp.update(user.getUid());
        log.info("登录成功:{}", loginParam.getUsername());
        cache.set("login_error_count", 0);

        new Logs(LogActions.LOGIN, loginParam.getUsername(), request.address(), user.getUid()).save();
    } catch (Exception e) {
        error_count += 1;
        cache.set("login_error_count", error_count, 10 * 60);
        String msg = "登录失败";
        if (e instanceof TipException) {
            msg = e.getMessage();
        } else {
            log.error(msg, e);
        }
        return RestResponse.fail(msg);
    }
    return RestResponse.ok();
}
 
Example #9
Source File: SessionManager.java    From blade with Apache License 2.0 4 votes vote down vote up
public Map<String, Session> sessionMap() {
    return sessionMap;
}
 
Example #10
Source File: SessionCleaner.java    From blade with Apache License 2.0 4 votes vote down vote up
private boolean expires(Session session) {
    long now = Instant.now().getEpochSecond();
    return session.expired() < now;
}
 
Example #11
Source File: TaleUtils.java    From tale with MIT License 2 votes vote down vote up
/**
 * 退出登录状态
 *
 * @param session
 * @param response
 */
public static void logout(Session session, Response response) {
    session.removeAttribute(TaleConst.LOGIN_SESSION_KEY);
    response.removeCookie(TaleConst.USER_IN_COOKIE);
    response.redirect(Commons.site_url());
}
 
Example #12
Source File: IndexController.java    From tale with MIT License 2 votes vote down vote up
/**
 * 注销
 *
 * @param session
 * @param response
 */
@Route(value = "logout")
public void logout(Session session, Response response) {
    TaleUtils.logout(session, response);
}
 
Example #13
Source File: SessionManager.java    From blade with Apache License 2.0 2 votes vote down vote up
/**
 * Get a Session instance based on the Session id
 *
 * @param id session id
 * @return Session instance
 */
public Session getSession(String id) {
    return sessionMap.get(id);
}
 
Example #14
Source File: RouteContext.java    From blade with Apache License 2.0 2 votes vote down vote up
/**
 * Get current request session, if null then create
 *
 * @return Return current session
 */
public Session session() {
    return this.request.session();
}
 
Example #15
Source File: Blade.java    From blade with Apache License 2.0 2 votes vote down vote up
/**
 * Get session implements Class Type
 *
 * @return return blade Session Type
 */
public Class<? extends Session> sessionType() {
    return this.sessionImplType;
}
 
Example #16
Source File: Blade.java    From blade with Apache License 2.0 2 votes vote down vote up
/**
 * Set session implements Class Type, e.g: RedisSession
 *
 * @param sessionImplType Session Type implement
 * @return return blade instance
 */
public Blade sessionType(Class<? extends Session> sessionImplType) {
    this.sessionImplType = sessionImplType;
    return this;
}