Resteasy PreProcessInterceptor用于记录请求属性(不是参数)

时间:2012-08-06 19:20:20

标签: resteasy

我们使用JBoss和Resteasy来实现Web服务,一个要求是我们在处理开始之前记录传递给Web服务的参数和属性。 PreProcessInterceptor非常适合这种情况。我有它工作并记录请求参数就好了,但有些信息将作为属性传递,我无法弄清楚如何访问它们。

下面是我用来记录请求参数的代码;谁能告诉我如何获得属性?

@Provider
@ServerInterceptor
public class ParameterLoggingInterceptor implements PreProcessInterceptor {
    @Inject
    private Logger logger;

@Override
public ServerResponse preProcess(HttpRequest request, ResourceMethod method) throws UnauthorizedException {
    StringBuilder sb = new StringBuilder();
    MultivaluedMap<String, String> mMap = request.getUri().getQueryParameters();
    Set<String> keys = mMap.keySet();
    int mapSize = keys.size();
    if (mapSize > 0) {
        sb.append("Incoming parameters: ");
        int processedParams = 1; 
        for (String key : keys) {
            sb.append(key).append("=");
            sb.append(mMap.get(key));
            if (processedParams < mapSize) {
                sb.append(", ");
            }
            processedParams++;
        }
        logger.debug(sb.toString());
    }
    return null;
}

编辑添加以下内容以回应Eiden的回答:

谢谢,艾登。我试了一下。你是说像下面这样的东西?如果是这样,它似乎不起作用(如果没有,请澄清)。 attributeName提供的是:“org.jboss.weld.context.AbstractConversationContext”,而attributeValue是相同的。这与使用org.jboss.resteasy.spi.HttpRequest对象时得到的结果相同。

@Provider
@ServerInterceptor
public class ParameterLoggingInterceptor implements PreProcessInterceptor {
    @Context HttpServletRequest servletRequest;

    @Inject
    private Logger logger;

@Override
public ServerResponse preProcess(HttpRequest request, ResourceMethod method) throws UnauthorizedException {
    Enumeration<String> attributeNames = servletRequest.getAttributeNames();
    StringBuilder sb = new StringBuilder();
    while (attributeNames.hasMoreElements()) {
        String attributeName = (String) attributeNames.nextElement();
        String attributeValue = (String) servletRequest.getAttribute(attributeName);
        // Do something with attributeValue and attributeName
    }
}

1 个答案:

答案 0 :(得分:4)

RestEasy可以将HttpServletRequest注入您的拦截器:

@Provider
@ServerInterceptor
public class ParameterLoggingInterceptor implements PreProcessInterceptor {
    @javax.ws.rs.core.Context HttpServletRequest servletRequest;

}

然后,您可以直接从HttpServletRequest - 方法访问preProcess,并提取满足您的日志记录要求所需的数据。