コンテキストとサーブレットの初期化パラメータ

コンテキストおよびサーブレットの初期化パラメーター

1. 概要

Servletsは、サーブレットコンテナで実行されるプレーンなJavaクラスです。

HTTPサーブレット(特定のタイプのサーブレット)は、Java Webアプリケーションの第一級市民です。 HTTPサーブレットのAPIはaimed at handling HTTP requests through the typical request-processing-response cycle, implemented in client-server protocolsです。

さらに、サーブレットは、要求/応答パラメーターの形式でキーと値のペアを使用して、クライアント(通常はWebブラウザー)とサーバー間の対話を制御できます。

これらのパラメーターは、初期化して、アプリケーション全体のスコープ(コンテキストパラメーター)およびサーブレット固有のスコープ(サーブレットパラメーター)にバインドできます。

このチュートリアルでは、how to define and access context and servlet initialization parametersを学習します。

2. サーブレットパラメータの初期化

アノテーションと標準のデプロイメント記述子(“web.xml”ファイル)を使用して、サーブレットパラメータを定義および初期化できます。 これらの2つのオプションは相互に排他的ではないことに注意してください。

これらの各オプションについて詳しく見ていきましょう。

2.1. 注釈を使用する

Initializing servlets parameters with annotations allows us to keep configuration and source code in the same place

このセクションでは、アノテーションを使用して特定のサーブレットにバインドされている初期化パラメータを定義してアクセスする方法を示します。

そのために、プレーンなHTMLフォームを介してユーザーデータを収集する単純なUserServletクラスを実装します。

まず、フォームをレンダリングするJSPファイルを見てみましょう。



    
        Context and Initialization Servlet Parameters
        
    
    
        

Please fill the form below:

EL(式言語)を使用してフォームのaction属性をコーディングしたことに注意してください。 これにより、サーバー内のアプリケーションファイルの場所に関係なく、常に“/userServlet”パスを指すことができます。

“$\{pageContext.request.contextPath}”sets a dynamic URL for the form, which is always relative to the application’s context path

最初のサーブレットの実装は次のとおりです。

@WebServlet(name = "UserServlet", urlPatterns = {"/userServlet"}, initParams={
@WebInitParam(name="name", value="Not provided"),
@WebInitParam(name="email", value="Not provided")}))
public class UserServlet extends HttpServlet {
    // ...

    @Override
    protected void doPost(
      HttpServletRequest request,
      HttpServletResponse response)
      throws ServletException, IOException {
        processRequest(request, response);
        forwardRequest(request, response, "/WEB-INF/jsp/result.jsp");
    }

    protected void processRequest(
      HttpServletRequest request,
      HttpServletResponse response)
      throws ServletException, IOException {

        request.setAttribute("name", getRequestParameter(request, "name"));
        request.setAttribute("email", getRequestParameter(request, "email"));
    }

    protected void forwardRequest(
      HttpServletRequest request,
      HttpServletResponse response,
      String path)
      throws ServletException, IOException {
        request.getRequestDispatcher(path).forward(request, response);
    }

    protected String getRequestParameter(
      HttpServletRequest request,
      String name) {
        String param = request.getParameter(name);
        return !param.isEmpty() ? param : getInitParameter(name);
    }
}

この場合、using initParams and the @WebInitParam annotationsによって2つのサーブレット初期化パラメータnameemailを定義しました。

HttpServletRequestのgetParameter()メソッドを使用してHTMLフォームからデータを取得し、getInitParameter()メソッドを使用してサーブレット初期化パラメータにアクセスしていることに注意してください。

getRequestParameter()メソッドは、nameおよびemail要求パラメーターが空の文字列であるかどうかを確認します。

空の文字列の場合、一致する初期化パラメータのデフォルト値が割り当てられます。

doPost()メソッドは、最初に、ユーザーがHTMLフォームに入力した名前と電子メール(存在する場合)を取得します。 次に、リクエストパラメータを処理し、リクエストを“result.jsp”ファイルに転送します。



    
        
        User Data
    
    
        

User Information

Name: ${name}

Email: ${email}

サンプルWebアプリケーションをApache Tomcat,Oracle GlassFishJBoss WidlFlyなどのアプリケーションサーバーにデプロイして実行すると、最初にHTMLフォームページが表示されます。

ユーザーがnameフィールドとemailフィールドに入力してフォームを送信すると、次のデータが出力されます。

User Information
Name: the user's name
Email: the user's email

フォームが空白の場合、サーブレットの初期化パラメーターが表示されます。

User Information
Name: Not provided
Email: Not provided

この例では、how to define servlet initialization parameters by using annotations, and how to access them with the getInitParameter() methodを示しています。

2.2. 標準デプロイメント記述子の使用

This approach differs from the one that uses annotations, as it allows us to keep configuration and source code isolated from each other

“web.xml”ファイルを使用して初期化サーブレットパラメータを定義する方法を紹介するために、最初にUserServletクラスからinitParamおよび@WebInitParamアノテーションを削除しましょう。

@WebServlet(name = "UserServlet", urlPatterns = {"/userServlet"})
public class UserServlet extends HttpServlet { ... }

次に、“web.xml”ファイルでサーブレット初期化パラメータを定義しましょう。



    
        UserServlet
        UserServlet
        
            name
            Not provided
        
        
            email
            Not provided
        
    

上に示したように、“web.xml”ファイルを使用してサーブレット初期化パラメータを定義すると、要約すると、<init-param>,<param-name>および<param-value>タグを使用することになります。

さらに、上記の標準構造に固執する限り、必要な数のサーブレットパラメータを定義することができます。

アプリケーションをサーバーに再デプロイして再実行すると、アノテーションを使用するバージョンと同じように動作するはずです。

3. コンテキストパラメータの初期化

Webアプリケーション全体でグローバルに共有およびアクセスする必要のある不変データを定義する必要がある場合があります。

データのグローバルな性質により、use application-wide context initialization parameters for storing the data, rather than resorting to the servlet counterpartsにする必要があります。

アノテーションを使用してコンテキスト初期化パラメータを定義することはできませんが、“web.xml”ファイルで定義できます。

アプリケーションが実行されている国と地方のデフォルトのグローバル値をいくつか提供するとします。

これは、いくつかのコンテキストパラメータで実現できます。

それに応じて“web.xml”ファイルをリファクタリングしましょう:


    
        province
        Mendoza
    
    
        country
        Argentina
    
    

今回は、<context-param>, <param-name>,タグと<param-value>タグを使用して、provincecountryのコンテキストパラメータを定義しました。

もちろん、UserServletクラスをリファクタリングして、これらのパラメーターをフェッチして結果ページに渡すことができるようにする必要があります。

サーブレットの関連セクションは次のとおりです。

@WebServlet(name = "UserServlet", urlPatterns = {"/userServlet"})
public class UserServlet extends HttpServlet {
    // ...

    protected void processRequest(
      HttpServletRequest request,
      HttpServletResponse response)
      throws ServletException, IOException {

        request.setAttribute("name", getRequestParameter(request, "name"));
        request.setAttribute("email", getRequestParameter(request, "email"));
        request.setAttribute("province", getContextParameter("province"));
        request.setAttribute("country", getContextParameter("country"));
    }

    protected String getContextParameter(String name) {-
        return getServletContext().getInitParameter(name);
    }
}

first gets the servlet context through getServletContext(), and then fetches the context parameter with the getInitParameter() methodであるgetContextParameter()メソッドの実装に注意してください。

次に、“result.jsp”ファイルをリファクタリングして、サーブレット固有のパラメーターとともにコンテキストパラメーターを表示できるようにする必要があります。

Name: ${name}

Email: ${email}

Province: ${province}

Country: ${country}

最後に、アプリケーションを再デプロイして、もう一度実行できます。

ユーザーがHTMLフォームに名前と電子メールを入力すると、コンテキストデータとともにこのデータが表示されます。

User Information
Name: the user's name
Email: the user's email
Province: Mendoza
Country: Argentina

それ以外の場合は、サーブレットとコンテキストの初期化パラメーターを出力します。

User Information
Name: Not provided
Email: Not provided
Province: Mendoza
Country: Argentina

この例は考案されていますが、how to use context initialization parameters to store immutable global dataを示しています。

データは特定のサーブレットではなくアプリケーションコンテキストにバインドされているため、getServletContext()メソッドとgetInitParameter()メソッドを使用して、1つまたは複数のサーブレットからデータにアクセスできます。

4. 結論

この記事では、we learned the key concepts of context and servlet initialization parameters and how to define them and access them using annotations and the “web.xml” file

かなり以前から、JavaではXML構成ファイルを削除し、可能な限りアノテーションに移行する傾向が強かった。

CDISpringHibernateは、いくつか例を挙げると、この明白な例です。

それでも、コンテキストとサーブレットの初期化パラメータを定義するために“web.xml”ファイルを使用することに本質的に問題はありません。

Servlet APIはこの傾向に向かってかなり速いペースで進化しましたが、we still need to use the deployment descriptor for defining context initialization parameters

いつものように、この記事に示されているすべてのコードサンプルは利用可能なover on GitHubです。