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

javaにおけるrequest.getSession(true、false、null)の違い

java 中 request.getSession(true/false/null)の違い

一、要求原因

現実世界では以下のようなことがよくあります。3中の用法:

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を返します。
セッションが適切に維持されることを確実にするために、レスポンスがコミットされる前にこのメソッドを呼び出す必要があります。コンテナがクッキーを使用してセッションの整合性を維持し、レスポンスがコミットされた際に新しいセッションを作成されるよう要求された場合、IllegalStateExceptionがスローされます。
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の場合は新しいセッションを作成し、そうでない場合はnullを返します;

簡而言之:

HttpServletRequest.getSession(true)は、HttpServletRequest.getSession()と同じです。 
HttpServletRequest.getSession(false)は、現在のセッションが存在しない場合nullを返します; 

3.      使用

セッションにログイン情報を保存または取得する際には、一般的には以下のように推奨されます:HttpSession session = request.getSession();

Sessionからログイン情報を取得する際には、一般的に以下のように推奨されます:HttpSession session = request.getSession(false);

4. より簡潔な方法

もしあなたのプロジェクトでSpringを使用している場合、Sessionの操作がとても便利になります。Sessionから値を取得する必要がある場合は、WebUtilsツール(org.springframework.web.util.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 != null63; session.getAttribute(name) : null); 
}

注:AssertはSpringツールキットの1つのツールで、特定の検証操作を判断するために使用されます。この例では、reqeustが空であるかどうかを判断し、空であれば例外を投げます。

あなたが使用する場合:

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

読んでいただきありがとうございます。皆様のサポートに感謝します!

おすすめ