从servlet设置错误消息和正文

Jer*_*amp 9 java servlets httpresponse

我想写一个servlet,它将返回一个http响应,如下所示:

HTTP/1.1 500 <short custom message>
Content-Length: ...

<longer custom message>
Run Code Online (Sandbox Code Playgroud)

原因是我希望程序化客户端能够处理响应消息以获取特定响应,但我还想用更长的解释来填充响应主体,以便使用浏览器轻松命中.

现在,HttpServletResponse有一个sendError(int,String)方法,允许我指定错误代码和消息.javadocs只说该消息将嵌入某种html页面,但没有关于设置http响应消息.调用此方法后,不允许您在响应中写入任何其他内容.在我的测试中(使用jetty),消息用于http响应和html主体,这对我来说没问题,除了我想指定两个不同的字符串,我不认为http响应的设置使用不同的实现保证消息.

还有一个setStatus(int)方法,您可以使用任何代码调用,然后您可以编写自己的html主体.这是关闭的,除了您不能指定http响应消息.

最后,有一个setStatus(int,String)方法实际上完全符合我的要求,但由于某种歧义而被弃用.我假设一些servlet容器正在将消息写入响应主体并关闭响应.

除了使用弃用的方法,我假设我已经搞砸了,但我很好奇是否有其他人知道任何技巧?

mat*_*t b 10

还有一个setStatus(int)方法,您可以使用任何代码调用,然后您可以编写自己的html主体.这是关闭的,除了您不能指定http响应消息.

是否有任何理由不使用response.setStatus(500)设置HTTP状态代码,然后写入响应的输出流?

这就是在最低级别实现"写入响应主体"的方式.

这是一个例子:

public class ErrorServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

        // 500 error
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        resp.getWriter().print("<html><head><title>Oops an error happened!</title></head>");
        resp.getWriter().print("<body>Something bad happened uh-oh!</body>");
        resp.getWriter().println("</html>");
    }
}
Run Code Online (Sandbox Code Playgroud)

web.xml中:

<web-app>
    <servlet>
        <servlet-name>myerror</servlet-name>
        <servlet-class>brown.testservlet.ErrorServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>myerror</servlet-name>
        <url-pattern>/myErrorPage</url-pattern>
    </servlet-mapping>
</web-app>
Run Code Online (Sandbox Code Playgroud)

并输出:

$ curl -I http://localhost:8080/testservlet/myErrorPage  
HTTP/1.1 500 Internal Server Error  
Content-Length: 108  
Server: Jetty(6.1.16)  

$ curl -v http://localhost:8080/testservlet/myErrorPage
* About to connect() to localhost port 8080 (#0)
*   Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /testservlet/myErrorPage HTTP/1.1
> User-Agent: curl/7.20.0 (i686-pc-mingw32) libcurl/7.20.0 OpenSSL/0.9.8k zlib/1.2.3
> Host: localhost:8080
> Accept: */*
>
< HTTP/1.1 500 Internal Server Error
< Content-Length: 108
< Server: Jetty(6.1.16)
<
<html><head><title>Oops an error happened!</title></head><body>Something bad happened uh-oh!</body></html>
* Connection #0 to host localhost left intact
* Closing connection #0
Run Code Online (Sandbox Code Playgroud)


FRo*_*owe 5

您可以通过在web.xml中指定错误特定页面来自定义错误页面:

<error-page>
  <error-code>500</error-code>
  <location>/error500.jsp</location>
</error-page>
Run Code Online (Sandbox Code Playgroud)

在jsp文件中,您可以使用请求属性来显示自定义消息和其他信息.