在spring xml中获取http请求或会话对象

时间:2012-11-20 16:49:21

标签: spring

我知道如何在Java代码中自动装配http请求对象:

@Resource
private HttpServletRequest request;

我想在xml conf中做类似的事情。我正在尝试实例化的bean将一个http会话对象作为构造函数参数:

    <bean class="..." scope="request">
        <constructor-arg>
             ???
        </constructor-arg>
    </bean>

1 个答案:

答案 0 :(得分:1)

您可以创建一个使用此方法的工厂类:

http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/context/request/RequestContextHolder.html#currentRequestAttributes%28%29

E.g:

<bean id="httpSessionFactory" class="HttpSessionFactory">
    <constructor-arg>true</constructor-arg>
</bean>

<bean class="..." scope="request">
    <constructor-arg>
        <bean factory-bean="httpSessionFactory"
              factory-method="getSession"/>
    </constructor-arg>
</bean>

和Java:

public class HttpSessionFactory {
    private boolean create;

    public HttpSessionFactory(boolean create) {
        this.create = create;
    }

    public static HttpSession getSession() {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return attr.getRequest().getSession(create);
    }
}