Program Tip

Tomcat에서 모든 기본 HTTP 오류 응답 콘텐츠 비활성화

programtip 2020. 11. 11. 20:34
반응형

Tomcat에서 모든 기본 HTTP 오류 응답 콘텐츠 비활성화


그것을 통해 내가 알고는 HTTP (404)과 같은 발생하면 기본적으로 Tomcat은 클라이언트에 일부 HTML 콘텐츠 등을 전송 web.xml<error-page> 구성 할 수 있습니다 이러한 콘텐츠를 사용자 정의 할 수 있습니다.

그러나 Tomcat 이 응답 내용과 관련 하여 아무것도 보내지 않기를 원합니다 (물론 상태 코드를 원합니다). 이것을 쉽게 구성 할 수있는 방법이 있습니까?

A) 내 서블릿의 응답 스트림에 빈 콘텐츠를 명시 적으로 보내는 것을 방지하고 B) 내 .NET에서 HTTP 오류 상태의 전체 무리에 대해 사용자 지정 오류 페이지를 구성하는 것을 방지하려고합니다 web.xml.

약간의 배경 지식을 위해 HTTP API를 개발 중이며 자체 응답 콘텐츠를 제어하고 있습니다. 예를 들어 HTTP 500의 경우 오류 정보가 포함 된 응답에 일부 XML 콘텐츠를 채 웁니다. HTTP 404와 같은 상황의 경우 HTTP 응답 상태는 클라이언트에 충분하며 tomcat이 보내는 콘텐츠는 필요하지 않습니다. 다른 접근 방식이 있다면 나는 그것을들을 수 있습니다.

편집 : 계속 조사한 후에도 여전히 해결책을 찾을 수 없습니다. 누군가 이것이 가능하지 않다고 확실히 말할 수 있거나 그것이 작동하지 않을 것이라는 증거가있는 자원을 제공 할 수 있다면, 나는 그것을 대답으로 받아들이고 그것을 해결하려고 노력할 것입니다.


바람둥이가 오류 페이지를 표시하지 않도록하려면 sendError (...)를 사용하지 마십시오. 대신 setStatus (...)를 사용하십시오.

예를 들어 405 응답을 제공하려면 다음을 수행하십시오.

response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);      
response.getWriter().println("The method " + request.getMethod() + 
   " is not supported by this service.");

또한 서블릿에서 예외가 발생하지 않도록하십시오. 대신 Exception을 포착하고 다시 statusCode를 설정하십시오.

protected void service(HttpServletRequest request,
      HttpServletResponse response) throws IOException {
  try {

    // servlet code here, e.g. super.service(request, response);

  } catch (Exception e) {
    // log the error with a timestamp, show the timestamp to the user
    long now = System.currentTimeMillis();
    log("Exception " + now, e);
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    response.getWriter().println("Guru meditation: " + now);
  }
}

물론 콘텐츠를 원하지 않는다면 작가에게 아무것도 쓰지 말고 상태 만 설정하면됩니다.


이것이 질문에 대한 "아무것도 보내지 않음"진술에 정확히 응답하지는 않지만 Clive Evans의 답변 물결 에서 나는 바람둥이에서 너무 많은 장황한 텍스트를 만들지 않고도 오류 페이지에서 벗어날 수 있음을 발견했습니다. 사용자 지정 ErrorReportValve.

"server.xml"에서 두 개의 매개 변수 "showReport"및 "showServerInfo"를 통해이 사용자 정의 ErrorReportValve를 수행 할 수 있습니다.

<Valve className="org.apache.catalina.valves.ErrorReportValve" showReport="false" showServerInfo="false" />

공식 문서 링크 .

tomcat 7.0.55에서 나를 위해 일했지만 tomcat 7.0.47에서 나를 위해 일하지 않았습니다 (다음 링크 http://www.mail-archive.com/users@tomcat.apache.org 에보 고 된 내용 때문에 생각합니다 . /msg113856.html )


Tomcat이 오류 본문을 보내는 것을 막는 빠르고 약간 더럽지 만 쉬운 방법은 tomcat 호스트에 대해 setErrorReportValveClass를 호출하는 것입니다. 즉 :

public class SecureErrorReportValve extends ErrorReportValve {

@Override
protected void report(Request request,Response response,Throwable throwable) {
}

}

다음으로 설정하십시오.

  ((StandardHost) tomcat.getHost()).setErrorReportValveClass(yourErrorValveClassName);

메시지를 보내고 싶은데 Tomcat이 메시지를 망쳐서는 안된다고 생각한다면 다음과 같은 내용을 원할 것입니다.

@Override
protected void report(final Request request, final Response response, final Throwable throwable) {
    String message = response.getMessage();
    if (message != null) {
        try {
            response.getWriter().print(message);
            response.finishResponse();
        } catch (IOException e) {
        }
    }
}

Heikki가 말했듯이 대신 상태를 설정하면 sendError()Tomcat이 응답 엔티티 / 본문 / 페이로드를 터치하지 않습니다.

제 경우처럼 엔터티없이 응답 헤더 만 보내려면

response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentLength(0);

트릭을 수행합니다. 를 사용 Content-Length: 0하면 다음 print()과 같이 사용하더라도 효과가 없습니다.

response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentLength(0);
response.getWriter().print("this string will be ignored due to the above line");

클라이언트는 다음과 같은 것을받습니다.

HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 0
Date: Wed, 28 Sep 2011 08:59:49 GMT

오류 메시지를 보내려면 setContentLength()with 메시지 길이 (0이 아닌)를 사용하거나 서버에 남겨 둘 수 있습니다.


서블릿 사양을 준수하지만 보안상의 이유로 바람둥이 또는 다른 서블릿 컨테이너가 오류 세부 정보를 보내는 것을 원하지 않습니다. 나는 이것도 약간 고생했다. 검색하고 시도한 후 솔루션은 다음과 같이 요약 할 수 있습니다.

  1. 다른 사람들이 언급했듯이을 sendError()사용 setStatus()하지 말고 대신 사용하십시오.
  2. 예를 들어 Spring Security와 같은 프레임 워크는 sendError()...
  3. write a Filter that
    a. redirects calls to sendError() to setStatus()
    b. flushes the response at the end to prevent the container from further modifying the response

A little example servlet filter doing this can be found here.


Why not just configure the <error-page> element with an empty HTML page?


Though this question is a bit old, I ran into this problem too. First of all, Tomcat's behavior is absolutely correct. This is per Servlet Spec. One should not alter Tomcat's behavior against the spec. As Heikki Vesalainen and mrCoder mentioned, use setStatus and setStatus only.

To whom it may concern, I have raised a ticket with Tomcat to improve the docs of sendError.


Configure <error-page> Elements in web.xml

Edit $CATALINA_HOME/conf/web.xml, add at the end the following <error-page>, save and restart tomcat

<web-app>

...
...
...

    <error-page>
        <error-code>404</error-code>
        <location>/404.html</location>
    </error-page>

    <error-page>
        <error-code>500</error-code>
        <location>/500.html</location>
    </error-page>

    <error-page>
        <error-code>400</error-code>
        <location>/400.html</location>
    </error-page>

</web-app>
  • It works great as I expect even though I didn't actually created a valid routes for those specified location values (e.g. /400.html)

before

enter image description here

after

enter image description here

참고URL : https://stackoverflow.com/questions/794329/disable-all-default-http-error-response-content-in-tomcat

반응형