controller中的session属性为null,但在jsp中它有值

时间:2017-05-13 08:36:46

标签: java spring jsp session model-view-controller

这是一个控制器login_action

    @RequestMapping(value = "/login_action")
    public ModelAndView login_action(@RequestParam("email") String email,@RequestParam("password") String password,RedirectAttributes redir){
        ModelAndView model=new ModelAndView("WEB-INF/view/index");
        Configuration con = new Configuration().configure().addAnnotatedClass(Users.class);
        SessionFactory sf=  con.buildSessionFactory();
        Session session = sf.openSession();
        Query q=session.createSQLQuery("SELECT User_ID,User_First_Name,User_Last_Name,Email,User_Type,Program,Level,Gender FROM Users  WHERE Email=:email AND Password=:password");
        q.setParameter("email",email);
        q.setParameter("password",password);
        Object u = (Object) q.uniqueResult();
        if(u==null) {
            model.addObject("view","login");
            model.addObject("errorMsg","Incorect Email or Password");
        }else {
                model=new ModelAndView("redirect:/profile");
                redir.addFlashAttribute("user",u);
        }
        return model;
    }

将用户设置为会话并在匹配电子邮件和密码后重定向到个人资料

    @RequestMapping(value="/profile")
    public ModelAndView profile(HttpSession session){
        Object [] o=(Object[])session.getAttribute("user");
        if(o==null){
            ModelAndView model =new ModelAndView("redirect:/login");
            return model;
        }
        ModelAndView model=new ModelAndView("WEB-INF/view/index");
        model.addObject("title",o[1]+" "+o[2]+" - Profile");
        model.addObject("view","profile");
        return model;
    }

当它被重定向到配置文件时,用户属性为null。因此,即使我已将用户设置为会话,它也会重定向到登录。

    @RequestMapping(value="/login")
    public ModelAndView login(){
        ModelAndView model=new ModelAndView("WEB-INF/view/index");
        model.addObject("title","Login");
        model.addObject("view","login");
        return model;
    }

但是在我的header.jsp中,用户设置在会话

    <c:choose>
    <c:when test="${user!=null}">
        <a>
            Welcome, ${user[1]} ||<a href="profile">profile</a></a> <a href="logout"/>Logout</a>
        </div>
    </c:when>
    <c:otherwise>
        <div>
            <a href="/"/>Home</a>||<a href="login"/>Login</a>||<a href="signup"/>Sign Up</a>
        </div>
    </c:otherwise>
    </c:choose>
    <hr>

但是当我点击配置文件的链接时,它可以正常工作 为什么? 登录页面: -

enter image description here

登录后,页面将重定向到配置文件并再次登录,因为用户在控制器中为空 但是标题改变是因为在jsp中用户有价值 enter image description here

当我点击个人资料时,它可以正常工作

enter image description here

0 个答案:

没有答案