获取没有注释参数的resteasy servlet上下文

时间:2012-11-22 15:39:42

标签: spring jsf-2 resteasy

快速项目说明:我们有一个基于JSF2 + Spring的动态数据源构建的应用程序。使用spring-config:

进行数据引用控制
<bean id="dataSource" class="com.xxxx.xxxx.CustomerRoutingDataSource">
....

和一个类(上面引用):

public class CustomerRoutingDataSource extends AbstractRoutingDataSource {

@Override
protected Object determineCurrentLookupKey() {
    return CustomerContextHolder.getCustomerType();
}

public Logger getParentLogger() throws SQLFeatureNotSupportedException {
    return null;
}
}

上面调用的CustomerContextHolder如下:

public class CustomerContextHolder {

private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();

public static void setCustomerType(String customerType) {
    contextHolder.set(customerType);
}

public static String getCustomerType() {

    String manager = (String)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("dataBaseManager");

    if (manager != null) {
        contextHolder.set(manager);
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("dataBaseManager", null);
    } else {
        String base =     (String)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("currentDatabBase");
        if (base != null)
            contextHolder.set(base);
    }
    return (String) contextHolder.get();
}

public static void clearCustomerType() {
    contextHolder.remove();
}
}

问题是最后一个人正在调用FacesContext.getCurrentInstance()来获取servlet上下文。只是为了解释,它使用会话属性dataBaseManager来告诉它应该使用哪个库。 对于实际的解决方案,它工作正常,但是通过RESTEASY Web服务的实现,当我们发出get请求时,FacesContext.getCurrentInstance()显然返回null并崩溃。

我搜索了很多,无法找到从@GET参数之外获取servlet-context的方法。我想知道是否有任何方法可以获得它,或者是否有其他解决方案来解决我的动态数据源问题。

谢谢!

1 个答案:

答案 0 :(得分:1)

像魔术一样,可能没有多少人知道。

我深入研究了Resteasy文档,发现了一个带有resteasy jar的springmvc插件的一部分,它有一个名为RequestUtil.class的类。 有了这个,我就可以使用方法getRequest()而无需“@Context HttpServletRequest req”参数。

使用它我可以在请求属性上设置所需的数据库,并从另一个线程(由spring调用)获取它并从正确的位置加载东西!

我现在使用它一个星期,它就像一个魅力。我唯一需要做的就是将上面的determineLookupKey()更改为:

    @Override
protected String determineCurrentLookupKey() {
    if (FacesContext.getCurrentInstance() == null) {
        //RESTEASY
        HttpServletRequest hsr = RequestUtil.getRequest();
        String lookUpKey = (String) hsr.getAttribute("dataBaseManager");
        return lookUpKey;
    }else{
        //JSF
        return CustomerContextHolder.getCustomerType();         
    }
}

希望这有助于其他人!

蒂亚戈

相关问题