Adobe AEM,如何从Apache felix OSGI服务获取SlingHttpServletRequest对象

时间:2014-12-14 03:14:49

标签: java osgi apache-felix aem

我正在使用Adobe AEM 6.0,而且还是Apache Felix和Sling的新手,我想知道如何从使用@Service注释的OSGI服务获取SlingHttpServletRequest的实例。

是否可以从ResourceResolverFactory或SlingRepository获取请求?

@Service
@Component(metatype = false)
public class TestServiceImpl implements  TestService{

    @Reference
    private ResourceResolverFactory resourceResolverFactory;
    @Reference
    private SlingRepository repository;

}

我知道SlingHttpServletRequest可以用于扩展SlingAllMethodsServlet的类,但是就我的要求而言,我需要编写服务而不是servlet。

我需要SlingHttpServletRequest的原因是因为我需要获取客户端的IP地址以进行审计记录。

有没有更好的方法呢?或者至少有人可以指导我指明如何达到这样的要求。

1 个答案:

答案 0 :(得分:1)

我认为Filter就是你所需要的。创建实现Filter的服务。每个Sling请求都会调用doFilter方法(如果 sling.filter.scope = REQUEST 当然)。
另请参阅Sling Filter

package com.examples.test.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(
    metatype = true,
    label = "Test Filter",
    immediate = true,
    enabled = true
)
@Service
@Properties({
    @Property(name = "sling.filter.scope", value = "REQUEST", propertyPrivate = true),
    @Property(name = "service.ranking", intValue = 100, propertyPrivate = true)
})
public class TestFilter implements Filter {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        //If you'll need some SlingHttpServletRequest functionality
        //SlingHttpServletRequest httpRequest = (SlingHttpServletRequest) request;

        log.info(request.getRemoteAddr());

        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        // TODO Auto-generated method stub
    }

}