我有非常简单的 JAX-RS WS:
@Stateless
@Path("/foo")
public class FooFacadeBean {
@GET
@Produces(MediaType.TEXT_HTML)
public String performFooCall(@Context HttpServletRequest request, @Context HttpServletResponse response) {
response.setStatus(500);
return "Hello";
}
}
部署后我执行:curl -v localhost:8080/foo,结果是:
About to connect() to localhost port 8080
Trying 127.0.0.1...
connected
Connected to localhost (127.0.0.1) port 8080
GET /foo HTTP/1.1
User-Agent: curl/7.26.0
Host: localhost:8080
Accept: */
HTTP/1.1 200 OK
X-Powered-By: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 3.1.2 Java/Sun Microsystems Inc./1.6)
Server: GlassFish Server Open Source Edition 3.1.2
Content-Type: text/html
Transfer-Encoding: chunked
Date: Thu, 26 Jul 2012 13:52:10 GMT
Hello
Connection to host localhost left intact
Closing connection
如您所见,HTTP 中的状态代码根本没有改变,尽管它是手动设置的。为什么会这样?我花了很多时间在谷歌上搜索,但没有任何结果。
诸如返回 Response 对象之类的解决方法,如下所示:
Response.status(404).entity("Hello").build();
完美运行!
Glassfish 使用 JERSEY 作为 JAX-RS 实现。我使用 Glassfish 的嵌入式变体。