zoukankan      html  css  js  c++  java
  • Servlet 第六课: Session的使用


    课程目标:

    通过这节课,我们能够学会加入session,学会调用session,以及大概懂得session存在的情况。


    课程具体:

    1.Session仅仅是存在于浏览器。比方我们打开浏览器获得我们所须要的session,我们在同一个浏览器再打开,我们所须要的这个session是还存在的。

      可是假设我们换用其它的浏览器或者直接关闭浏览器,那么这个session就会过期。

    2.Session
    –Session 是用来跟踪用户当前状态的一种机制,是针对浏览器和server的一对一关系。
    –Session 的一般使用方法是,在用户登录时将用户的登录信息保存到session中,以便以后使用。

    3.Session 接口HttpSession


    通常我们仅仅使用HttpSession接口,接口的实现由web容器来完毕
    –能够从HttpServletRequest中获得HttpSession
    request.getSession();
    –将信息保存在HttpSession中
    session.setAttribute(“UserSession”,obj);【特别注意:这里是能够直接存放obj对象的,打个例如我们这里能够直接存放一个user对象】


    –从HttpSession中获得信息
    session.getAttribute(“UserSession”);
    –使HttpSession失效
    session.invalidate();

    4.实例解说:

    事实上这个session的使用我认为和cookie的使用基本差点儿相同。


    设置Session Servlet
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	  HttpSession session = request.getSession();    
              session.setAttribute("session_name", "session_value");  
    }
    
     获得Session Servlet
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	HttpSession session = request.getSession();  
    	String value = (String)session.getAttribute("session_name");
    	System.out.println(value);
    }

    5. Session 实例,登录Session

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		//为了获取前台传过来的数据:username and password
            String username = request.getParameter("username");
    		String password = request.getParameter("password");
    		//调用dao的实现逻辑:比方要验证用户账号和密码是否正确
    		//假设正确,再通过username和password查询出全部须要的信息,然后再封装成一个user对象
    		UserDao dao = new UserDaoImpl();
    		User u = dao.login(username, password);
    
    		
    		if(u!=null){
    			//推断,假设用户存在,就封装一个user对象,发给jsp
    			HttpSession session = request.getSession();
    			session.setAttribute("user", u);
    			request.getRequestDispatcher("welcome.jsp").forward(request, response);
    		}else{
    			//推断,假设用户不存在,那么直接跳转到错误页面
    			request.getRequestDispatcher("error.html").forward(request, response);
    		}
    
    	}



  • 相关阅读:
    而立之年的程序员创业者,写给不甘平凡的自己和80、90后!
    无焦虑,不成长!三大方法让你走出焦虑!
    [Chat]实战:仿网易云课堂微信小程序开发核心技术剖析和经验分享
    [干货教程]仿网易云课堂微信小程序开发实战经验
    微信公众号支付之坑:调用支付jsapi缺少参数 timeStamp等错误解决方法
    微信支付之扫码支付开发:我遇到的坑及解决办法(附:Ecshop 微信支付插件)
    OpenCV 4.3 编译和配置
    OpenCV 之 基本绘图
    OpenCV 之 空间滤波
    Qt 地址薄 (二) 添加地址
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/3897795.html
Copyright © 2011-2022 走看看