使用MessageContext的自定义响应消息

时间:2014-06-09 10:50:21

标签: java rest jax-ws httpresponse

我想知道如何为MessageContext设置自定义响应消息?我知道如何在服务器端设置HTTP_RESPONSE_CODE200404等,以及如何在客户端读取它们。但是,如何设置自定义消息,例如“错误请求,密钥和值不能为空”?是否有任何旨在用于创建自定义响应消息的内容?

服务器

@WebServiceProvider
@ServiceMode(value = Service.Mode.PAYLOAD)
public class MWServiceProvider implements Provider<Source> {

    @javax.annotation.Resource(type=WebServiceContext.class)
    private WebServiceContext wsContext;

    @Override
    public Source invoke(Source source) {
        MessageContext messageContext = wsContext.getMessageContext();
        ...
        // read the source content, which is a key-value-pair for this example
        if (keyValuePair.getKey().isEmpty() || keyValuePair.getValue().isEmpty()) {
            // bad request, key or value can not be empty
            messageContext.put(MessageContext.HTTP_RESPONSE_CODE, HttpURLConnection.HTTP_BAD_REQUEST);
            // ??? HOW CAN I SET A CUSTOM MESSAGE LIKE 
            // ??? "Bad request, key and value can not be empty"
            // ??? TO MY MESSAGE RESPONSE CONTEXT?
        } else {
            ...
            messageContext.put(MessageContext.HTTP_RESPONSE_CODE, HttpURLConnection.HTTP_OK);
            ...
        }
        return source;
    }
    ...
}

在客户端读取状态代码:

Map<String, Object> response = dispatch.getResponseContext();
Integer statusCode = (Integer) response.get(MessageContext.HTTP_RESPONSE_CODE);
System.out.println("status_code: " + statusCode);

1 个答案:

答案 0 :(得分:1)

您可以通过javax.servlet.http.HttpServletResponse中的密钥MessageContext.SERVLET_RESPONSE访问基础MessageContext。从那里你应该能够设置error code and message