0

次のようにサーブレットからデータを取得するクラスがあります。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");{
        ServletOutputStream  out = response.getOutputStream();
        try {
            out.println("<html><head><title>" +  "</title></head>");
            out.println("<body><h1>" +  "</h1>");
            name = request.getParameter("username" );
            message = "hi there";
            //String  comment = request.getParameter( "comment" );
            out.println("Name:" + name + "<BR>");
            //out.println("Comment: " + comment + "<BR>");
        }
        catch(Throwable  t ) {
            out.println("<P><pre>");
            t.printStackTrace( new PrintStream(out) );
            out.println ("</pre><P>");
        }
        out.println ("</body></html>");
    }
}

それはうまくいきますが、サーバー上の別のクラスでも name パラメータを使用したいと考えています。次のようなものを使用できますか:

getServletContext().setAttribute("package", "name");

そして、そのようなクラスから属性を呼び出しますか? または、値をサーブレットコンテキストまたはサーブレットに保存して、再度呼び出すことができる別の方法はありますか? 私が本当にやりたいのは、サーブレットがロードされた後、どこかで処理された最後の値を保持し、必要に応じて別のクラスで使用することだけです。

すべてのヘルプに感謝します!! :)

4

1 に答える 1

1

getServletContext()サーブレット間でデータを共有する方法の1つです。だから、はい、あなたのアプローチはうまくいくはずです。

データがユーザーに固有である場合は、を使用するのgetServletContext()ではなく、を使用することをお勧めしますHttpSession

于 2012-07-18T11:53:26.570 に答える