java web request_Java Web request.getSession()方法

Session在网络应用中被称为会话。

具体到web中的Session指的就是用户在浏览某个网站时,从进入网站到浏览器关闭所经过的这段时间,也就是用户浏览这个网站所花费的时间,因此从概述上我们可以看到,session实际上是一个特定的时间概念。

需要注意的是:一个session的概念需要包括特定的客户端,特定的服务器端以及不中断的操作时间。A用户和C服务器建立连接时所处的session同B用户和C服务器建立连接时所处的Session是两个不同的session。

在HttpServlet中,getSession(boolean create)意思是返回当前reqeust中的HttpSession ,如果当前reqeust中的HttpSession为null,当create为true,就创建一个新的Session,否则返回null;

简而言之:

HttpServletRequest.getSession(ture) 等同于HttpServletRequest.getSession();

HttpServletRequest.getSession(ture) , 如果当前Session没有就创建一个新的Session;

HttpServletRequest.getSession(false) , 如果当前Session没有就为null;

问题和bug:// 如果session不存在的话又创建了一个

HttpSession session = request.getSession();

String user_name = session.getAttribute("user_name");

需要注意的地方是request.getSession() 等同于request.getSession(true),除非我们确认session一定存在或者sesson不存在时明确有创建session的需要,否则尽量使用request.getSession(false)。在使用request.getSession()函数,通常在action中检查是否有某个变量/标记存放在session中。这个场景中可能出现没有session存在的情况,正常的判断应该是这样:HttpSession session = request.getSession(false);

if (session != null) {

String user_name = session.getAttribute("user_name");

}

Spring对Session的处理:

如果项目中用到了Spring(其实只要是Java的稍大的项目,Spring是一个很好的选择),对session的操作就方便多了。如果需要在Session中取值,可以用WebUtils工具(org.springframework.web.util.WebUtils)的getSessionAttribute(HttpServletRequest request, String name)方法。/**

* Check the given request for a session attribute of the given name.

* Returns null if there is no session or if the session has no such attribute.

* Does not create a new session if none has existed before!

* @param request current HTTP request

* @param name the name of the session attribute

* @return the value of the session attribute, or null if not found

*/

public static Object getSessionAttribute(HttpServletRequest request, String name) {

Assert.notNull(request, "Request must not be null");

HttpSession session = request.getSession(false);

return (session != null ? session.getAttribute(name) : null);

}

注:Assert是Spring工具包中的一个工具,用来判断一些验证操作,本例中用来判断reqeust是否为空,若为空就抛异常。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值