SpringMVC存取Session的两种方法

目录

方法一:使用servlet-api

@Controller
public class ManagerController {

    @Resource
    private ManagerService managerServiceImpl;

    @RequestMapping(value = "manager/login.do",method = RequestMethod.GET)  
    public ModelAndView login(ManagerModel managerModel,HttpSession httpSession){

        ManagerModel manager = managerServiceImpl.getManager(managerModel);
        if(manager!=null){
            manager.setPassword("");
            httpSession.setAttribute("manager", manager);
            return new ModelAndView(new RedirectView("../admin/main.jsp"));
        }else{
            return new ModelAndView(new RedirectView("../admin/login.jsp"));
        }
    }

    @RequestMapping(value = "manager/logout.do",method = RequestMethod.GET)
    public String logout(HttpSession httpSession){
        httpSession.getAttribute("manager");
        return "success";
    }
}

方法二:使用SessionAttributes

@Controller
@SessionAttributes("manager")
public class ManagerController {

    @Resource
    private ManagerService managerServiceImpl;

    @RequestMapping(value = "manager/login.do",method = RequestMethod.GET)  
    public ModelAndView login(ManagerModel managerModel,ModelMap model){

        ManagerModel manager = managerServiceImpl.getManager(managerModel);
        if(manager!=null){
            manager.setPassword("");
            model.addAttribute("manager", manager);
            return new ModelAndView(new RedirectView("../admin/main.jsp"));
        }else{
            return new ModelAndView(new RedirectView("../admin/login.jsp"));
        }
    }

    @RequestMapping(value = "manager/logout.do",method = RequestMethod.GET)
    public String logout(@ModelAttribute("manager")ManagerModel managerModel){
        return "success";
    }
}

ps:多个session使用注解的话,@SessionAttributes允许指定多个属性。你可以通过字符串数组的方式指定多个属性,如 @SessionAttributes({“attr1”,”attr2”})

文章最后编辑时间为:2017-08-06 14:49:49

标签: spring mvc session spring

声明:本博客如无特殊说明皆为原创,转载请注明来源:SpringMVC存取Session的两种方法谢谢!

相关文章

精彩评论
  1. huhu huhu  Windows 7 x64 Edition Google Chrome 57.0.2950.5

    icon_biggrin.png icon_biggrin.png

发表评论:

icon_question.pngicon_razz.pngicon_sad.pngicon_evil.pngicon_exclaim.pngicon_smile.pngicon_redface.pngicon_biggrin.pngicon_surprised.pngicon_eek.pngicon_confused.pngicon_cool.pngicon_lol.pngicon_mad.pngicon_twisted.pngicon_rolleyes.pngicon_wink.pngicon_idea.pngicon_arrow.pngicon_neutral.pngicon_cry.pngicon_mrgreen.png