Java_Session和登陆

本文详细阐述了在Servlet中检查session是否为空的方法,并在session存在时执行请求处理操作,否则将用户重定向至登录页面。同时介绍了session失效时的清理操作及异常处理机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//In every servlet, check whether Session is null or not. If session is not null then only do the request processing else redirect to login page.

 

HttpSession session  = request.getSession();

if(Session !=null)

{

try

{

    // acutal servlet actions

}else

{

  // redirect to login page

}

 

//Also it would be good if you add null check for session in your above code.

 

HttpSession session  = request.getSession();

if(session !=null)

try

{

    session.removeAttribute("logonData");//logonData,such as user and so on

    session.invalidate();

    // redirect tologin page

catch (Exception sqle)

{

    // ...

}

}else

{

  //session already null/ expired

}

 

ps: below is something from session api

 

void invalidate()

Invalidates this session then unbinds any objects bound to it.

Throws:

IllegalStateException - if this method is called on an already invalidated session

 

void removeAttribute(String name)

Removes the object bound with the specified name from this session. If the session does not have an object bound with the specified name, this method does nothing.

After this method executes, and if the object implements HttpSessionBindingListener, the container calls HttpSessionBindingListener.valueUnbound. The container then notifies any HttpSessionAttributeListeners in the web application.

Parameters:

name - the name of the object to remove from this session

Throws:

IllegalStateException - if this method is called on an invalidated session

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值