views:

35

answers:

2

I have a web-application in java, spring framework, hibernate on tomcat, that has basically almost no security except the login and logout functionality (no spring security)

I can access the user information in a controller by:

// where request is HttpServletRequest
 HttpSession session = request.getSession(true);
 SystemUser user = (SystemUser) session.getAttribute("user");

and do the logic. However, I need to get this information in Dao layer. Where I actually get data from the database to retrieve user specific data. One way is to pass the "user" object to service layer and then service layer to pass it on to the dao layer. But this is quite a huge load of work.

I wonder if there is a way in Spring some how to access the session object in Dao layer? or any other way to retrieve user specific data.

+1  A: 

You can use RequestContextHolder:

ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpSession session = requestAttributes.getRequest().getSession();

Because it uses a static method, it can be invoked from anywhere, as long as it's from the same thread that handled the request.

Edit: As Faisal correctly pointed out, this is generally not a good idea, since it leads to undesirable coupling and hard-to-test code. However, in some cases it's unavoidable, such as when the interface to your code is fixed (e.g. legacy services, or a JSP tag library, etc).

skaffman
It is a very bad practice to use presentation layer objects like Request/Session inside Business Logic Layer and/or Data Access Layer. This bounds your layers to presentation objects and will cause issues while changing the presentation layer, scaling your application etc.
Faisal Feroz
@Faisal: I agree. However, that was the question that was asked, and this is the answer. If you think this is the incorrect answer to the question, by all means downvote, but if you're objecting to the question itself, then take your downvote elsewhere, please.
skaffman
while i support skaffman on that, but i also feel that as an experienced developer, Skaffman should've indicated in his answer that the practice is a bad one.
anirvan
@anirvan: Edited accordingly.
skaffman
@skaffman I have undone the down vote as well.
Faisal Feroz
+2  A: 

This might just be my personal opinion but you are far better passing this type of information along as a method parameter rather than accessing web context classes in your DAO.

What if you want to use your DAO classes outside of a web application?

The DAO accessing some sort of request context holder makes the question of what data the DAO method needs to run a hidden secret - rather than declaring a method parameter for the data it needs, it is accessing a static method on some class secretly.

This leads to hard-to-test and hard-to-understand code.

matt b