0

我有一个使用 Spring MVC 用 Ja​​va 编写的简单应用程序。Credentials 类只包含登录时提供的用户名和密码。

理想情况下,我希望每个 jsp 页面上都显示人员的用户名和全名。我正在考虑设置会话属性。

我的控制器类:

@RequestMapping(value = "/menu", method=RequestMethod.POST)
    public String addContact(Map<String, Object> map,@ModelAttribute("user")
    User user, BindingResult result, SessionStatus status,HttpSession session) {


session.setAttribute("DisplyName", u.getDisplayName());

我的 JSP:

 <div class="wlctxt">Welcome <%=session.getAttribute("DisplyName") %></div>

但是我在这里得到会话属性的空值。

有没有其他方法可以实现这一目标?

4

1 回答 1

0

您不需要输入会话属性 DisplayName。您对每个请求都执行此操作。您有模型属性,它将被放入请求中,因此您可以在 jsp 中访问它:

<div class="wlctxt">Welcome <c:out value="${user.displayName}"/></div>

参加会议有很多你必须关心的麻烦。如果您的用户更改显示名称怎么办?您应该在会话中更新。或者更关键的是:更改某些访问权限?在每个可能的地方都可以轻松地在会话中进行更新。

我通过我可以从内存缓存中获取的内容(从性能的角度从 DB expansibe 读取)放入会话 userId,然后执行以下操作:

@Controller
public class SomeController {

    @Autowired
    private UserService userService;

    @RequestMapping(...)
    public String getSomePage(HttpServletRequest request, HttpSession session) {
        Long userId = (Long) session.getAtribute("currentUserId");
        User user = userService.get(userId);
        request.setAttribute("currentUser", user);
    }

在jsp中你可以访问它:

<div>Wellcome <c:out value="${currentUser.displayName}"/>!</div>
于 2012-05-08T06:11:03.260 回答