English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

الفرق بين request.getSession(true،false،null) في java

الفرق بين request.getSession(true/false/null) في java

السبب الأول

في الواقع، نحن نواجه دائمًا ما يلي من الاستخدامات الثلاثة:

HttpSession session = request.getSession();

HttpSession session = request.getSession(true);

HttpSession session = request.getSession(false);

الفرق الثاني

1.                 Servlet الرسمي يقول:

public HttpSession getSession(boolean create)
تعود جلسة HttpSession الحالية المرتبطة بهذا الطلب أو، إذا لم يكن هناك جلسة حالية و create = true، تعود جلسة جديدة.
إذا كان create = false ولم يكن لدى الطلب جلسة HttpSession صالحة، فإن هذا الطريقة تعود null.
To make sure thesession is properly maintained, you must call this method before the responseis committed. If the Container is using cookies to maintain session integrityand is asked to create a new session when the response is committed, anIllegalStateException is thrown.
Parameters: true -to create a new session for this request if necessary; false to return null ifthere's no current session
Returns: theHttpSession associated with this request or null if create is false and therequest has no valid session

2.      翻译过来的意思是:

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

简而言之:

HttpServletRequest.getSession(ture)等同于 HttpServletRequest.getSession() 
HttpServletRequest.getSession(false)等同于 如果当前Session没有就为null; 

3.      使用

عند إدخال أو استخراج معلومات الlogueة من Session، يُنصح عادةً: HttpSession session = request.getSession();

عند الحصول على معلومات الlogueة من Session، يُنصح عادةً: HttpSession session = request.getSession(false);

4.     طريقة أكثر بسيطة

إذا كنت تستخدم Spring في مشروعك، سيكون من السهل التعامل مع session. إذا كنت بحاجة إلى إخراج قيمة من Session، يمكنك استخدام مكتبة WebUtils (org.springframework.web.util.WebUtils) عبر طريقة WebUtils.getSessionAttribute(HttpServletRequest request, String name);، انظر إلى الكود المصدر:

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 هل هو فارغ، إذا كان فارغًا يرفع استثناء

عندما تستخدمونها:

WebUtils.setSessionAttribute(request, "user", User);
User user = (User)WebUtils.getSessionAttribute(request, "user");

شكرًا على القراءة، آمل أن تساعدكم، شكرًا لدعمكم لهذا الموقع!

توصيات لك