views:

514

answers:

2

I have a JSP struts application that uses Spring to integrate with the services/dao/database. Basically, struts uses spring to get the data from the DB, it builds the form and forward them to the JSP files.

I have a header file that is injected in each JSP file using Tiles. I would like to show "Welcome John Doe" on each page inside the header. Where "John Doe" is the name of the currently logged user.

What would be the best approach to do that? The solution that I can think of is:

  1. Use a Spring Filter the catch the http request. Load the user from the database using a cookie that contains the user id(*) and put the name in a session bean named "CurrentUser"

  2. In "header.jsp", get the spring application context. Using it, load the bean "CurrentUser" and get the name. Put the name in the html.

I think I could get this to work. But I'm not certain this is the best way to do it. Any thought on my approach?


(*) Of course, the cookie will be encrypted

A: 

Are you not already storing some sort of User object in Session?

If so, I would just add a "getFullName()" method to this domain object and have the DAO populate it when it returns it. Ideally you should populate the User object when the user logs in, store it in session, and not need to load all of the user's details again from the database on each and every page request.

(Are you not using Spring Security? If so, they provide a pretty simple way to store a UserDetails-like object in Session, and easy access to it.)

I'd vote against both of your approaches because

  1. This means (at least) an extra database call per page request
  2. This wouldn't work if other users shared the same bean in the same context. Also, you really shouldn't have JSP files (which are your presentation layer) interacting with data services directly.
matt b
My approach would not do a database request each time. I would populate a session bean using a filter. Session bean are managed by spring and are attached to the session.
Thierry-Dimitri Roy
A: 

Although it may be an extremely large hammer for your fairly simple use-case, we have gotten a really neat spring-jsp integration (jsp 2.1 required!) by using ELResolver. By following this tutorial you can basically inject any spring managed bean into your el-context and allow it to be accessed using jsp-el like this:

${spring.mybean.myproperty}

You can choose to inject pre-defined beans into your el-context or simply pass "mybean" to getBean and allow almost anything spring-managed to be accessible from jsp. mybean could easily be a session-scoped spring bean.

I'm not totally sure how this would align with tiles, though.

krosenvold