Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Session User Info retrieval in Dao layer

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.

like image 529
Saky Avatar asked Nov 30 '22 09:11

Saky


2 Answers

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).

like image 155
skaffman Avatar answered Dec 05 '22 01:12

skaffman


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.

like image 40
matt b Avatar answered Dec 04 '22 23:12

matt b