English 中文(简体)
如何在Spring/Struts框架的JSP头文件中展示用户的全名最佳方式是什么?
原标题:
  • 时间:2009-05-12 18:57:01
  •  标签:

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.

我有一个通过Tiles注入到每个JSP文件中的头文件。我希望在头文件内的每页上显示“欢迎John Doe”。其中,“John Doe”是当前登录用户的名称。

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

  1. 使用Spring过滤器来捕获http请求。使用包含用户ID(*)的cookie从数据库中加载用户,并将名称放置在名为“CurrentUser”的会话Bean中。 (*)用户ID - 用户的唯一标识符。

  2. 在“header.jsp”中获取Spring应用程序上下文。使用它加载“CurrentUser” bean并获取名称。将名称放入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?


当然,这个cookie将被加密。

最佳回答

虽然它可能对于您相对简单的用例来说是非常大的锤子,但我们通过使用ELResolver获得了非常好的spring-jsp集成(需要jsp 2.1!)。通过遵循此教程,您可以将任何spring管理的bean注入到el-context中,并允许像这样使用jsp-el访问它:

${spring.mybean.myproperty}

您可以选择将预定义的bean注入到您的el-context中,或者只需传递“mybean”给getBean并允许几乎任何受Spring管理的jsp访问。 mybean很容易成为一个session-scoped spring bean。

我不完全确定这将如何与瓷砖对齐。

问题回答

你不已经在Session中存储了某种类型的User对象吗?

如果是这样,我只需为此域对象添加一个“getFullName()”方法,当DAO返回它时,它会填充它。理想情况下,应在用户登录时填充User对象,将其存储在会话中,而不需要在每个页面请求上再次从数据库中加载所有用户详细信息。

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

我会投票反对你们两种方法,因为

  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.




相关问题
热门标签