java - Setting both error message and body from servlet -
i want write servlet return http response so:
http/1.1 500 <short custom message> content-length: ... <longer custom message>
the reason want programmatic client able process response message take particular response want fill in response body longer explanation it's easy hit using browser.
now, httpservletresponse has senderror(int, string) method allows me specify error code , message. javadocs message embedded in kind of html page, nothing setting http response message. after calling method, not allowed write else response. in tests (with jetty), message used both http response , html body, fine me, except want specify 2 different strings , don't think setting of http response message guaranteed different implementation.
there's setstatus(int) method can call code, , can write own html body. close, except can't specify http response message.
finally, there's setstatus(int, string) method want, it's deprecated due kind of ambiguity. i'm assuming servlet containers writing message response body , closing response.
aside using deprecated method, i'm assuming i'm screwed here, i'm curious if else knows tricks?
there's setstatus(int) method can call code, , can write own html body. close, except can't specify http response message.
is there reason why not use response.setstatus(500)
set http status code, followed writing response's output stream?
this how "writing response body" achieved @ lowest level.
here's example:
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 error happened!</title></head>"); resp.getwriter().print("<body>something bad happened uh-oh!</body>"); resp.getwriter().println("</html>"); } }
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>
and output:
$ 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 * connect() localhost port 8080 (#0) * trying 127.0.0.1... connected * connected localhost (127.0.0.1) port 8080 (#0) > /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 error happened!</title></head><body>something bad happened uh-oh!</body></html> * connection #0 host localhost left intact * closing connection #0
Comments
Post a Comment