2016-08-25 52 views
0

我想将登录消息分享给其他方法,但不知道如何。所以我用无法将ModelMap添加到会话中

春天注释@SessionAttributes的控制器,并尝试addAttribute

保存userModelMap。但是,当我在另一种方法使用@ModelAttribute

我的浏览器抛出: 500 - Expected session attribute 'user'

这里是我的控制器:

@Controller 
@RequestMapping("/login") 
@SessionAttributes("user") 
public class Login { 
    @Resource 
    private UserSer userSer; 

    @RequestMapping("/main") 
    @ResponseBody 
    public String login (@RequestBody User user, ModelMap map) { 
     boolean result = userSer.login(user); 
     String view = "fail"; 

     if(result) { 
      map.addAttribute("user", user); 
      view = "success"; 
     } 

     return view; 
    } 


     //It doesn't work 
     @RequestMapping("/logout") 
     public String logout(@ModelAttribute("user") User user) { 
      System.out.println(user.getUsername()); 
      return "success"; 
     } 

    } 

我需要配置web.xml中。

回答

0

从登录方法中删除@ResponseBody。当您使用@ResponseBody时,返回值会直接写入响应。在这种情况下,Spring无法腾出时间来创建Session对象并保存到模型属性中。

+0

它的工作,但我需要在'$ .ajax'中添加一些代码。我可以同时使用模型属性和'@ ResponseBody'吗?可能吗。 –

+0

我没有得到你的问题。你想实现什么? – abaghel

+0

如果我使用'@ ResponseBody',我可以将'user'保存到Session对象吗? –