I think this is something like what the answer you linked to was getting at:
Warning: None of this has been compiled. None of this has been tested.
The CurrentRequestFilter
is run once per request. It is responsible for storing the current request in a ThreadLocal
that will be used later on.
public class CurrentRequestFilter extends OncePerRequestFilter {
private ThreadLocal<HttpServletRequest> currentRequest;
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {
currentRequest.set(request);
filterChain.doFilter(request, response);
}
public ThreadLocal<HttpServletRequest> getCurrentRequest() {
return currentRequest;
}
public void setCurrentRequest(ThreadLocal<HttpServletRequest> currentRequest) {
this.currentRequest = currentRequest;
}
}
The CurrentRequestDataSource
has access to the same ThreadLocal
as the CurrentRequestFilter
.
public class CurrentRequestDataSource extends AbstractRoutingDataSource {
private ThreadLocal<HttpServletRequest> currentRequest;
@Override
protected DataSource determineTargetDataSource() {
HttpServletRequest request = currentRequest.get();
String url = ...;
String username = ...;
String password = ...;
DataSource dataSource = ...;
return dataSource;
}
@Override
protected Object determineCurrentLookupKey() {
return null;
}
public ThreadLocal<HttpServletRequest> getCurrentRequest() {
return currentRequest;
}
public void setCurrentRequest(ThreadLocal<HttpServletRequest> currentRequest) {
this.currentRequest = currentRequest;
}
}
You would then configure your bean definitions something like this:
<bean id="currentRequest" class="java.lang.ThreadLocal"/>
<bean id="currentRequestFilter" class="CurrentRequestFilter">
<property name="currentRequest" ref="currentRequest"/>
</bean>
<bean id="dataSource" class="CurrentRequestDataSource">
<property name="currentRequest" ref="currentRequest"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
You must then make sure that the CurrentRequestFilter
is registered in your web.xml
file:
<filter>
<filter-name>Current Request Filter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetBeanName</param-name>
<param-value>currentRequestFilter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Current Request Filter</filter-name>
<servlet-name>Name_Of_Your_Servlet</servlet-name>
</filter-mapping>
Again, none of this has been tested, but hopefully it can offer some guidance.