spring MVC 如何获取session并实现传值到前台

以前经常使用SSH框架,对spring MVC只是有所了解,但是当真正使用springMVC做开发的时候却发现,一个简单的获取session的问题竟然纠结了许久:

花点时间记录一下,以便日后重用:

后台获取session:

@RequestMapping("/usrlogin")
public ModelAndView usrlogin(@RequestParam String usrid,
            @RequestParam String passwd) {
        HttpSession session = getSession();
        User user = new User();
        user = userMapper.getUserByUsridAndPasswd(usrid, passwd);
        if (null != user) {
            session.setAttribute("user", user.getUser_id());
//            User user1=(User)session.getAttribute("user");
//            System.out.println(user1.getUser_name());
            
            return new ModelAndView("main");
        } else {
            return new ModelAndView("error");
        }
    }
       
       
public static HttpSession getSession() { 
    HttpSession session = null; 
    try { 
        session = getRequest().getSession(); 
    } catch (Exception e) {} 
        return session; 
} 
    
public static HttpServletRequest getRequest() { 
    ServletRequestAttributes attrs =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 
    return attrs.getRequest(); 
} 

前台jsp取值:

 <%
        HttpSession s = request.getSession();     
  %>

<span><%=s.getAttribute("user")%></span>

 

  

posted @ 2014-08-23 17:31  暖暖的拥抱  阅读(29565)  评论(0编辑  收藏  举报