64

Webアプリから返されたすべてのHTTPステータスコードについて報告しようとしています。ただし、ステータスコードは、ServletResponseを介して、またはHttpServletResponseにキャストした場合でもアクセスできないようです。ServletFilter内でこの値にアクセスする方法はありますか?

4

7 に答える 7

91

まず、ステータスコードをアクセス可能な場所に保存する必要があります。応答を実装でラップし、そこに保持するのが最善です。

public class StatusExposingServletResponse extends HttpServletResponseWrapper {

    private int httpStatus;

    public StatusExposingServletResponse(HttpServletResponse response) {
        super(response);
    }

    @Override
    public void sendError(int sc) throws IOException {
        httpStatus = sc;
        super.sendError(sc);
    }

    @Override
    public void sendError(int sc, String msg) throws IOException {
        httpStatus = sc;
        super.sendError(sc, msg);
    }


    @Override
    public void setStatus(int sc) {
        httpStatus = sc;
        super.setStatus(sc);
    }

    public int getStatus() {
        return httpStatus;
    }

}

このラッパーを使用するには、サーブレットフィルターを追加する必要があります。レポートを作成できますか。

public class StatusReportingFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        StatusExposingServletResponse response = new StatusExposingServletResponse((HttpServletResponse)res);
        chain.doFilter(req, response);
        int status = response.getStatus();
        // report
    }

    public void init(FilterConfig config) throws ServletException {
        //empty
    }

    public void destroy() {
        // empty
    }

}
于 2009-08-19T19:32:07.770 に答える
65

サーブレット3.0以降、がありHttpServletResponse#getStatus()ます。

したがって、アップグレードの余地がある場合は、サーブレット3.0(Tomcat 7、Glassfish 3、JBoss AS 6など)にアップグレードすれば、ラッパーは必要ありません。

chain.doFilter(request, response);
int status = ((HttpServletResponse) response).getStatus();
于 2010-11-29T15:35:15.663 に答える
17

また、#sendRedirectのラッパーを含める必要があり、ステータスを「0」ではなく「200」に初期化することをお勧めします。

private int httpStatus = SC_OK;

...

@Override
public void sendRedirect(String location) throws IOException {
    httpStatus = SC_MOVED_TEMPORARILY;
    super.sendRedirect(location);
}
于 2010-12-20T00:35:44.833 に答える
12

上記のDavidの回答に欠けていることの1つは、他の形式のsendErrorもオーバーライドする必要があるということです。

@Override
public void sendError(int sc, String msg) throws IOException {
    httpStatus = sc;
    super.sendError(sc, msg);
}
于 2009-09-30T02:52:20.597 に答える
8

Davidの答えに加えて、resetメソッドをオーバーライドすることもできます。

@Override
public void reset() {
    super.reset();
    this.httpStatus = SC_OK;
}

...および非推奨のsetStatus(int、String)

@Override
public void setStatus(int status, String string) {
    super.setStatus(status, string);
    this.httpStatus = status;
}
于 2011-10-19T14:58:25.307 に答える
6

HttpServletResponseWrapperを作成し、すべてのsetStatus()、sendError()、およびsendRedirect()メソッドをオーバーライドしてすべてをログに記録します。リクエストごとにラッパーを応答オブジェクトに交換するフィルターを作成します。

于 2009-08-19T19:21:18.197 に答える
0

古いコンテナで立ち往生している場合は、実際のステータスコードを使用するDavid Rabinowitzの代替ソリューション(ラッパーを使用して設定した後に変更された場合)は次のとおりです。

public class StatusExposingServletResponse extends HttpServletResponseWrapper {

    public StatusExposingServletResponse(HttpServletResponse response) {
        super(response);
    }

    @Override
    public void sendError(int sc) throws IOException {
        super.sendError(sc);
    }

    @Override
    public void sendError(int sc, String msg) throws IOException {
        super.sendError(sc, msg);
    }

    @Override
    public void setStatus(int sc) {
        super.setStatus(sc);
    }

    public int getStatus() {
        try {
            ServletResponse object = super.getResponse();

            // call the private method 'getResponse'
            Method method1 = object.getClass().getMethod("getResponse");
            Object servletResponse = method1.invoke(object, new Object[] {});

            // call the parents private method 'getResponse'
            Method method2 = servletResponse.getClass().getMethod("getResponse");
            Object parentResponse = method2.invoke(servletResponse, new Object[] {});

            // call the parents private method 'getResponse'
            Method method3 = parentResponse.getClass().getMethod("getStatus");
            int httpStatus = (Integer) method3.invoke(parentResponse, new Object[] {});

            return httpStatus;
        }
        catch (Exception e) {
            e.printStackTrace();
            return HttpServletResponse.SC_ACCEPTED;
        }
    }

    public String getMessage() {
        try {
            ServletResponse object = super.getResponse();

            // call the private method 'getResponse'
            Method method1 = object.getClass().getMethod("getResponse");
            Object servletResponse = method1.invoke(object, new Object[] {});

            // call the parents private method 'getResponse'
            Method method2 = servletResponse.getClass().getMethod("getResponse");
            Object parentResponse = method2.invoke(servletResponse, new Object[] {});

            // call the parents private method 'getResponse'
            Method method3 = parentResponse.getClass().getMethod("getReason");
            String httpStatusMessage = (String) method3.invoke(parentResponse, new Object[] {});

            if (httpStatusMessage == null) {
                int status = getStatus();
                java.lang.reflect.Field[] fields = HttpServletResponse.class.getFields();

                for (java.lang.reflect.Field field : fields) {
                    if (status == field.getInt(servletResponse)) {
                        httpStatusMessage = field.getName();
                        httpStatusMessage = httpStatusMessage.replace("SC_", "");
                        if (!"OK".equals(httpStatusMessage)) {
                            httpStatusMessage = httpStatusMessage.toLowerCase();
                            httpStatusMessage = httpStatusMessage.replace("_", " ");
                            httpStatusMessage = capitalizeFirstLetters(httpStatusMessage);
                        }

                        break;
                    }
                }
            }

            return httpStatusMessage;
        }
        catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    private static String capitalizeFirstLetters(String s) {

        for (int i = 0; i < s.length(); i++) {
            if (i == 0) {
                // Capitalize the first letter of the string.
                s = String.format("%s%s", Character.toUpperCase(s.charAt(0)), s.substring(1));
            }

            if (!Character.isLetterOrDigit(s.charAt(i))) {
                if (i + 1 < s.length()) {
                    s = String.format("%s%s%s", s.subSequence(0, i + 1), 
                            Character.toUpperCase(s.charAt(i + 1)), 
                            s.substring(i + 2));
                }
            }
        }

        return s;

    }

    @Override
    public String toString() {
        return this.getMessage() + " " + this.getStatus();
    }

}

警告:プライベートデータ値を取得するために卑劣なリフレクションとイントロスペクションを使用する場合のクラス階層の多くの仮定。

于 2011-08-04T17:44:25.037 に答える