You can, but I would use a simple POJO just to keep things clean. Keep in mind that the value stored in singleton will only be accessible by the same thread that processed the servlet request, so if you do any asynchronous processing, you will need to consider this. Here's a super basic impl:
public class OrgId { public static ThreadLocal<Integer> orgId = new ThreadLocal<Integer>(); }
Since the organizational identifier is in the session, you can set the ThreadLocal value in an early servlet filter like this (not many errors):
public class OrgIdFilter implements Filter { public void doFilter(ServletRequest servletrequest, ServletResponse servletresponse, FilterChain filterchain) throws java.io.IOException, javax.servlet.ServletException { int orgId = 0; HttpServletRequest req = (HttpServletRequest) servletRequest; HttpSession session = req.getSession(); orgId = Integer.parseInt(session.getAttribute("OrganizationalIdAttr")); try { OrgId.orgId.set(orgId); filterChain.doFilter(servletRequest, servletresponse); } finally { OrgId.orgId.set(null);
This assumes that orgId is in session when the filter is called, but if not, you get the idea ....
Then in your interceptor (or almost anywhere) you can get the current orgId stream with:
OrgId.orgId.get();
The potential snafu here is that all of these components (filter, OrgId and interceptor) must be loaded by the same class loader to ensure that the OrgId class is effectively a singleon, otherwise with multiple ThreadLocal instances hanging around it will not work sequentially or in general. Needless to say, all this must happen in the same virtual machine.
I'm not sure if this is the cleanest way to solve this problem, but it really gives you your orgId where you need it.
Nicholas
source share