简体   繁体   中英

Best way to store/retrieve frequently used data from the HttpSession

I have a standard GAE app with Java servlets. I want to implement user role functionality throughout the system. For this purpose I want to retrieve user role from the database and store it in the session, in such a way all servlets will have access to this data. I read some articles about it and the basic way to do it is to use Filters to populate HttpSession with necessary data. However, in this case I should retrieve data from the HttpSession in every servlet in the same way, which results in code duplicates. Evident solution for this problem is just to derive from HttpServlet class and create own Servlet with necessary methods for working with HttpSession (eg protected Role getUserRole()). This makes the usage of the Filters pointless. Is there any reason to use Filters in this case?

You should have a top level filter, which maps to /* . This filter will do the fetching of role from database , if not present in session. Now you extend HttpServletRequest and create a wrapper overriding isUserInRole() method, so that role is fetched as you like. Create an object of this request object and use in chain.doFilter in Filter.

So all Servlets can just call request.isUserInRole() to check roles

You can have a main servlet that directly inherit from HttpServlet, this servlet knows how to get the user roles from the HttpSession via protected Role getUserRole() . All other servlets within your application should then subclass that main servlet to have the common functionality available to them.

Servlet filters get invoked prior to the invocation of any other servlet, the main purpose of filters is to decorate the requests/responses before handing them over to the servlets for further processing. You have the choice of accessing your database from within the filters and populate the HttpSession accordingly, then each servlet will know how to retrieve that information from the HttpSession later on.

The other option that I recommend here is to populate the HttpSession with the user roles from within the first servlet that process the request (you could have another common method of the main servlet to do that, eg protected void populateUserRole(HttpSession httpSession)).

Cheers;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM