SpringMVC中 Session的使用情況


在SpringMVC中,使用Session可以用通過兩種方式

  1、servlet-api 即HttpSession 

     session.setAttritute(),session.getAttribute();

  2、使用@sessionAttributes()注解

   ①Spring框架會在調用完Controller之后、渲染View之前檢查Model的信息,並把@SessionAttributes()注釋標明的屬性加入session中

   ②@ModelAttribute在聲明Controller的參數的時候,可以用來表明此參數引用某個存在在Model中的對象,如果 這個對象已經存在於Model中的話(Model可以在調用Controller之前就已經保存有數據,這應該不僅僅因為 HandlerInterceptor或者@ModelAttribute標記的方法已經顯式的將一些對象加入到了Model對象中,也因為Spring會默認將一些對象加入到Model中,這一點很重要)。    

    ③如果Session中已經存在某個對象,那么可以直接使用ModelAttribute聲明Controller的參數,在Controller中可以直接使用它。

eg.1

@Controller
public class ManagerController {
 
    @RequestMapping(value = "/login",method = RequestMethod.GET)  
    public ModelAndView login(HttpSession httpSession){

           httpSession.setAttribute("username", "admin");
         return new ModelAndView("login");
    }
    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String logout(HttpSession httpSession){
         String name=httpSession.getAttribute("username");
      return "success";
}

 eg.2

@Controller
@SessionAttributes("username")
public class ManagerController {
    
    @RequestMapping(value = "/login",method = RequestMethod.GET)  
    public ModelAndView login(Model model)
            model.addAttribute("username", "admin");
            return new ModelAndView("login");
      
    }
    
    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String logout(@ModelAttribute("username") String name){
    System.out.println(name);
    return "success"; } }

參考鏈接:http://www.cnblogs.com/waytofall/p/3460533.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM