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);
    		}
    
    	}



  • 相关阅读:
    mysqlp批量替换的sql语句
    Paypal 支付功能的 C# .NET / JS 实现
    Layui table 组件的使用:初始化加载数据、数据刷新表格、传参数
    WinForm DataGridView 绑定泛型List(List<T>)/ArrayList不显示的原因和解决
    entity framework codefirst 用户代码未处理DataException,InnerException基础提供程序在open上失败,数据库生成失败
    《设计模式》一书中的23种设计模式
    C++程序实例唯一方案,窗口只打开一次,程序只打开一次
    重构——与设计模式的恋情
    重构——一个小例子
    C#通过调用WinApi打印PDF文档类,服务器PDF打印、IIS PDF打印
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/3897795.html
Copyright © 2011-2022 走看看