【问题标题】:Jersey with Spring AOP带有 Spring AOP 的泽西岛
【发布时间】:2011-12-30 20:24:55
【问题描述】:

我希望我的 AOP 建议能够处理当前正在执行的 Jersey 资源的 HttpContext。 spring-annotations 示例提到用户可以获取请求并进行身份验证等,但是如何获取通知中上下文中的任何值?

目前我的资源定义如下所示:

    @Singleton
    @Path("/persist")
    public class ContentResource {

        @PUT
        @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
        @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
        @Auth
        public Content save(Content content){
           //Do some thing with the data
        }
    }

方面是这样定义的:

    @Aspect
    public class AuthorizeProcessor {

        @Around(value="@annotation(package.Auth) and @annotation(auth)", argNames = "auth")
        public Object authorize(ProceedingJoinPoint pjp, Auth auth) throws Throwable{
            //How do I get the HttpContext here?
            return pjp.proceed();
        }
    }

【问题讨论】:

    标签: jersey spring-aop


    【解决方案1】:

    当然这很可能为时已晚,但我通过在执行授权的服务前面实现一个 Servlet 过滤器来完成您正在做的事情。这完全避免了对 AOP 的需求,它直接为您提供了实际的 ServletRequest,而无需绕过系统来获取它。

    具有讽刺意味的是,如果您真的想要 AOP,那么您帮助我回答的 question 可能会在这里对您有所帮助。

    您可以为请求提供 Spring RequestContextFilter,然后访问 HttpServletRequest(而不是 HttpContext):

    <filter>
        <filter-name>requestContextFilter</filter-name>
        <filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>requestContextFilter</filter-name>
        <url-pattern>/path/to/services/*</url-pattern>
    </filter-mapping>
    

    访问过滤器链中的代码:

    /**
     * Get the current {@link HttpServletRequest} [hopefully] being made
     * containing the {@link HttpServletRequest#getAttribute(String) attribute}.
     * @return Never {@code null}.
     * @throws NullPointerException if the Servlet Filter for the {@link
     *                              RequestContextHolder} is not setup
     *                              appropriately.
     * @see org.springframework.web.filter.RequestContextFilter
     */
    protected HttpServletRequest getRequest()
    {
        // get the request from the Spring Context Holder (this is done for
        //  every request by a filter)
        ServletRequestAttributes attributes =
            (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
    
        return attributes.getRequest();
    }
    

    【讨论】:

    • 哈,哈。那是一个年轻的我:)。我最终使用ResourceFilterFactory 来解决这个问题。谢谢!
    猜你喜欢
    • 2016-01-27
    • 2013-01-12
    • 2018-03-25
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 2011-12-30
    相关资源
    最近更新 更多