8

独自のバージョンのHttpSessionをJavaで実装する必要があります。そのような偉業をどのように達成するかを説明する情報はほとんど見つかりませんでした。

私の問題は、アプリケーションサーバーの実装に関係なく、既存のHttpSessionをオーバーライドするにはどうすればよいかということだと思います。

私は質の高いものに出くわしましたが、かなり古い読み物であり、目標を達成するのに役立ちます-http://java.sun.com/developer/technicalArticles/Servlets/ServletControl/

他にアプローチはありますか?

4

3 に答える 3

8

その2つの方法。

HttpSession独自のHttpServletRequestWrapper実装でオリジナルを「ラッピング」します。

Hazelcast と Spring Session を使用して分散セッションをクラスタリングするために、これを少し前に作成しました。

ここはかなりうまく説明されています。

まずは自分で実装HttpServletRequestWrapper

public class SessionRepositoryRequestWrapper extends HttpServletRequestWrapper {

        public SessionRepositoryRequestWrapper(HttpServletRequest original) {
                super(original);
        }

        public HttpSession getSession() {
                return getSession(true);
        }

        public HttpSession getSession(boolean createNew) {
                // create an HttpSession implementation from Spring Session
        }

        // ... other methods delegate to the original HttpServletRequest ...
}

その後、独自のフィルターから元の をラップし、サーブレット コンテナーによって提供されるHttpSession内に配置します。FilterChain

public class SessionRepositoryFilter implements Filter {

        public doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
                HttpServletRequest httpRequest = (HttpServletRequest) request;
                SessionRepositoryRequestWrapper customRequest =
                        new SessionRepositoryRequestWrapper(httpRequest);

                chain.doFilter(customRequest, response, chain);
        }

        // ...
}

最後に、web.xml の先頭にフィルタを設定して、他のフィルタよりも先に実行されるようにします。

それを実現する 2 番目の方法は、サーブレット コンテナにカスタム SessionManager を提供することです。

たとえば、Tomcat 7では。

于 2016-01-28T01:54:47.027 に答える
5

新しいクラスを作成し、HttpSession を実装します。

public class MyHttpSession implements javax.servlet.http.HttpSession {

    // and implement all the methods

}

免責事項:私はこれを自分でテストしていません:

次に、url-pattern が /* および extend であるフィルターを作成しますHttpServletRequestWrapper。ラッパーはカスタムHttpSessionクラスを に返す必要がありますgetSession(boolean)。フィルターでは、独自の を使用しますHttpServletRequestWrapper

于 2011-08-21T17:08:01.203 に答える
1

HttpSession の実装は J2EE コンテナーによって提供されるため、さまざまなコンテナー間で機能する移植可能な方法で簡単に実行できるようには思えません。

ただし、同様の結果を得るには、 javax.servlet.Filter および javax.servlet.HttpSessionListener を実装し、Hazelcast および Tomcat を使用した Spring Boot で説明されているように、フィルターで ServletRequest および ServletResponse をラップします。

于 2014-12-29T23:06:55.053 に答える