SlingHttpServletRequest

SlingHttpServletRequest

我正在使用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地址以用于审核日志记录目的。

有没有更好的方法可以做到这一点?或者至少有人可以帮我指出正确的方向,以实现我的要求。

最佳答案

我认为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
    }

}

关于java - Adobe AEM,如何从Apache felix OSGI服务获取SlingHttpServletRequest对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27465968/

10-10 09:22