【Axis2】Axis2 で、HttpServletRequest を取得するには

Axis2 で、HttpServletRequest を取得するには

MessageContext context = MessageContext.getCurrentMessageContext();
HttpServletRequest request = 
    (HttpServletRequest) context.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);

■ 用途

 * Axis2で作成したサーバにおいて...

 (1) 以下のURLに書かれているようなクライアント証明書情報を取得する場合
http://syo.cocolog-nifty.com/freely/2007/06/apachetomcatssl_d908.html
http://www.fireproject.jp/feature/uzumi/ssl/client-cert-webapp.html
http://memoyasu.blogspot.jp/2011/11/tomcat-6windows-x64-filter.html
 (2) クッキーを取得する場合
 (3) クライアントのIPアドレスを取得する場合

# String ip = (String) context.getProperty(MessageContext.REMOTE_ADDR);
http://d.hatena.ne.jp/kokuzawa/20091007/1254880496

■ 注意

MessageContext.getCurrentMessageContext()からnullが返る場合
以下のように
MessageContext context = MessageContext.getCurrentMessageContext();
で実行したら、「context = null」になってしまった場合

解決案

http://axis.apache.org/axis2/java/core/docs/axis2config.html#Service_Configuration
にある services.xml の scope="soapsession" (or scope="transportsession"も?)にすればいいかと。

また、以下も気になる。
http://space.geocities.jp/nequomame/java/webservice/webservice_93_02.html
より抜粋

soapsessionスコープのセッション管理を有効とするための設定について 
soapsessionスコープの場合、Webサービスのセッション管理を有効とするには、
setManageSessionメソッドの呼び出しに加え、addressingモジュールを有効にする必要があるようです。
そのために、上記のようなコードを記述してaddressingモジュールを有効にするための設定を行っています。

■ サンプル

Axis2Helper.java

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.axis2.context.MessageContext;
import org.apache.axis2.transport.http.HTTPConstants;

public class Axis2Helper {
    public static HttpServletRequest getHttpServletRequest() {
        MessageContext context = MessageContext.getCurrentMessageContext();
        return (HttpServletRequest) context.getProperty(
                HTTPConstants.MC_HTTP_SERVLETREQUEST);
    }

    public static java.security.cert.X509Certificate getCertificate() {
        HttpServletRequest request = Axis2Helper.getHttpServletRequest();
        java.security.cert.X509Certificate[] certificate = 
            (java.security.cert.X509Certificate[]) request.getAttribute(
                        "javax.servlet.request.X509Certificate");
        if (certificate != null) {
            return certificate[0];
        }
        // Certificate was not found
        return null;
    }
    
    public static Cookie getCookieByKey(String key) {
        HttpServletRequest request = Axis2Helper.getHttpServletRequest();
        
        for (Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals(key)) {
                return cookie;
            }
        }
        return null;
    }
    
    public static String getCookieValueByKey(String key) {
        Cookie cookie = Axis2Helper.getCookieByKey(key);
        
        if (cookie != null) {
            return cookie.getValue();
        }
        return null;
    }
}