zoukankan      html  css  js  c++  java
  • 7.用户登陆,用户退出,记住用户名和密码

    一.会话技术

        1.1.什么是会话?

            会话: 为了实现某一个功能, 客户端和服务器之间可能会产生多次的请求和响应, 从客户端访问服务器开始, 到最后访问服务器结束, 客户端关闭为止, 这期间产生的多次请求和响应加在一起就称之为是客户端和服务器之间的一次会话

            HTTP协议规定一次请求一次响应后断开连接,每一次请求都是一个崭新的请求.但是一次会话往往需要跨越多个请求,如何保存在每次请求中产生的临时数据,是必须要解决的一个问题.解决方案有2种:

    一种是将临时数据保存在客户端浏览器上,用户每次访问时,将会话的临时数据在请求中带给服务器;(Cookie)

    另一种方案是将会话数据保存在服务器上,给每个用户一个身份标识,根据用户的身份标识,找到保存在服务器上的数据.(Session)

        1.2.如何来保存会话过程中产生的数据?

            ~requset域太小

            ~ServletContext域太大

    二.Cookie

        -----------------------------------------------

        2.1.Cookie概述

            Cookie的原理是通过Set-Cookie响应头和Cookie请求头将会话中产生的数据保存在客户端

            Set-Cookie

            Cookie

            客户端请求服务器, 服务器将需要保存的数据通过Set-Cookie响应头发给客户端, 客户端收到后会将数据保存在浏览器的内部

            当客户端再次请求服务器时, 通过Cookie请求头将上次保存的数据再带给服务器, 服务器通过Cookie头来获取数据, 通过这种方式可以保存会话中产生的数据.

            Cookie是将需要保存的数据保存在了客户端, 是客户端技术. 每个客户端各自保存各自的数据, 再次访问服务器时会带着自己的数据, 每个客户端持有自己的数据, 因此就不会发生混乱了

        -----------------------------------------------

        2.2.实现Cookie

            SUN公司为了简化Cookie的开发, 提供了如下操作Cookie的API:

            -------------------------------------------

            2.2.1.创建Cookie

                Cookie cookie = new Cookie(String name, String value);

                getName()

                getvalue()

                setValue()

            -------------------------------------------

            2.2.2.添加Cookie

                response.addCookie(Cookie cookie);

                    //向响应中添加一个Cookie, 可以在一次响应中添加多个Cookie

            -------------------------------------------

            2.2.3.获取Cookie

                Cookie [] cs = requset.getCookies();

                    //返回请求中所有Cookie组成的数组, 如果请求中没有任何Cookie信息, 则返回null.

            -------------------------------------------

            2.2.4.设置Cookie存活时间

                setMaxAge();//指定Cookie保存的时间, 以秒为单位

                    //如果不明确的指定, Cookie默认是会话级别的Cookie, Cookie会保存在浏览器的内存中, 一旦浏览器关闭, Cookie也会随着浏览器内存的释放而销毁.

                    //通过setMaxAge()方法可以设置Cookie的存活时间, 设置了存活时间后, Cookie将会以文件的形式保存在浏览器的临时文件夹中, 在指定的时间到来之前, 即使多次开关浏览器, Cookie信息也会一直存在.

            -------------------------------------------

            2.2.5.设置Cookie路径

                setPath(String path);  

                    //设置当前Cookie在浏览器访问哪一个路径及其子孙路径的时候带回来

                    //如果当前请求的url是该Cookie的path属性的路径,或者是子路径,则携带当前Cookie,否则不携带

                    //如果不指定, 默认的path值就是发送Cookie的Servlet的所在的路径

                    //客户端浏览器识别一个Cookie不止通过其name,而是通过该Cookie的域名+路径+name来识别一个Cookie

                    lastTime+/day13+localhost

                    lastTime+/day13/servlet+localhost            

            -------------------------------------------

            ~~2.2.6.设置domain(不推荐设置)

                setDomain(xxx);

                设置浏览器访问哪一个域名时带着当前Cookie

                现在的浏览器一般都拒绝接受第三方的Cookie, 甚至有的浏览器只要发现Cookie被设置了domain, 不管是不是第三方Cookie, 也会拒绝接受! 所以最好不要设置这个方法!

            -------------------------------------------

            2.2.7.删除Cookie

                没有直接删除Cookie的方法!!!

                如果想要删除一个Cookie, 可以向浏览器发送一个 同名 同path 同domain的Cookie, 只需要将Cookie的maxAge设置为0, 由于浏览器是根据 名+path+domain 来区分Cookie的, 所以当两个cookie的上述条件相同时, 浏览器就会认为是同一个Cookie, 那么后发的Cookie会覆盖之前的, 而后发的Cookie的存活时间为0, 所以浏览器收到后也会立即删除!!

            -------------------------------------------

            ~2.2.8.Cookie的细节:

                一个Cookie只能标识一种信息,它至少含有一个标识该信息的名称(NAME)和设置值(VALUE)。

                一个WEB站点可以给一个WEB浏览器发送多个Cookie,一个WEB浏览器也可以存储多个WEB站点提供的Cookie。

                浏览器一般只允许存放300个Cookie,每个站点最多存放20个Cookie,每个Cookie的大小限制为4KB/1KB。

                Cookie是每个浏览器独立保存的

        -----------------------------------------------

        2.3.案例: 在页面中显示上次访问时间(略)

        -----------------------------------------------

        2.4.案例: EasyMall登录功能之记住用户名

            2.4.1.编写LoginServlet, 代码实现如下:

      String remname = request.getParameter("remname");      
    
                //记住用户名
                if("true".equals(remname)){
                    Cookie remnameCookie = new Cookie("remname", URLEncoder.encode(username, "utf-8"));
                    //设置最大生存时间(保存30天)
                    remnameCookie.setMaxAge(3600*24*30);
                    //设置path, 让浏览器访问当前WEB应用下任何一个资源都能带Cookie!!
                    remnameCookie.setPath(request.getContextPath()+"/");
                    //将Cookie添加到response中发送给浏览器
                    response.addCookie(remnameCookie);              
                }else{//取消记住用户名 -- 删除Cookie
    
                    Cookie remnameCookie = new Cookie("remname", "");
                    remnameCookie.setMaxAge(0);
                    remnameCookie.setPath(request.getContextPath()+"/");
                    response.addCookie(remnameCookie);
                }

            2.4.2.编写login.jsp, 从Cookie中获取用户名存入用户名输入框     

     <%
                    //获取Cookie中的用户名
                    Cookie[] cs = request.getCookies();
                    Cookie remnameCookie = null;
                    if(cs != null){
                        for(Cookie c : cs){
                            if("remname".equals(c.getName())){
                                remnameCookie = c;
                            }
                        }
                    }
                    String username = "";
                    if(remnameCookie != null){
                        username = URLDecoder.decode(remnameCookie.getValue(), "utf-8");
                    }
                 %>
    

            2.4.3.勾选记住用户名复选框

                <input type="checkbox" name="remname" value="true"

                    <%= remnameCookie == null ? "" : "checked='checked'" %>

                />记住用户名

    三.Session

        -----------------------------------------------

        3.1.Session概述

            Session是将会话中产生的数据保存在了服务器端, 是服务器端技术

            Session是一个域对象

                setAttribute(String name, Object value);

                getAttribute(String name);

                removeAttribute(String name)

                getAttributeNames()

             

                生命周期:

                    当第一次调用request.getSession()方法时创建Session

                   超时: 如果一个Session超时30分钟(可以在web.xml中来修改, 在根目录下通过<session-config>来配置)未被使用, 则认为Session超时, 销毁session

                    自杀: 当调用session.invalidate()方法的时session立即销毁!!

                    意外身亡: 当服务器非正常关闭时, 随着应用的销毁, session销毁. 当服务器正常关闭, 则未超时的session将会以文件的形式保存在tomcat服务器work目录下, 这个过程叫做session的钝化. 当服务器再次启动时, 钝化着的session还可以恢复过来, 这个过程叫做session的活化。

                   

                作用范围: 当前会话范围

                   

                主要功能: 保存当前会话相关的数据

        -----------------------------------------------

        3.2.Session的原理

            Session是基于一个JSESSIOINID的Cookie工作的

            -------------------------------------------

            3.2.1.怎么解决浏览器关闭之后, 无法使用浏览器关闭之前的Session??

                (注意: 在访问一个jsp时, 默认一上来就会创建session!!)

            -------------------------------------------

            3.2.2.禁用Cookie的情况下使用Session

                URL重写: 就是在传入的URL地址后拼接JSESSIOINID返回一个新的地址, 用来在禁用Cookie的情况下用url地址来携带JSESSIOINID

                    response.encodeURL(String url);

                    //--如果是普通的地址用这个方法

                    response.encodeRedirectURL(String url);

                    //--如果地址是用来进行重定向的,用这个方法

        -----------------------------------------------

        3.3.案例: 实现购物车(略)

        -----------------------------------------------

        3.4.案例: Easymall登陆功能的实现

            所谓的登陆, 就是在检查用户提交的用户名和密码之后, 对于通过校验的用户, 在session中保存一个登陆标记, 从而在访问其他页面的时候, 可以通过在session中获取用户的登陆标记, 来判断当前用户的登陆状态

            -------------------------------------------

            3.4.1.导入登陆页面

                将登陆页面及相关的css及图片拷贝到工程中. 用jsp代替html展示数据

            -------------------------------------------

            3.4.2.编辑login.jsp页面

                (1) 修改首页头部中的登陆超链接, 将url地址指向login.jsp

                (2) 修改login.jsp中的url地址, 将相对路径改为绝对路径

                (3) 修改表单提交地址, 将表单提交到LoginServlet

            -------------------------------------------

            3.4.3.实现后台注册代码

                (1) 创建LoginServlet, 处理登陆请求

                (2) 编写LoginServlet, 代码实现如下:

                    //1.处理乱码

                    request.setCharacterEncoding("utf-8");

                    //2.获取请求参数

                    String username = request.getParameter("username");

                    String password = request.getParameter("password");

                    String remname = request.getParameter("remname");

                    //3.记住用户名(见上)

                   

                    //4.登陆用户

                    rs = ps.executeQuery();

                    if(rs.next()){

                        //去登陆

                        request.getSession().setAttribute("user", username);

                        //登陆成功, 跳转到首页

                        response.sendRedirect(request.getContextPath()+"/index.jsp");

                    }else{

                        //用户名或密码不正确, 转发回登陆页面提示

                        request.setAttribute("msg", "用户名或密码不正确");

                        request.getRequestDispatcher("/login.jsp").forward(request, response);

                        return;

                    }

                (3) 编写login.jsp, 在登陆table中添加行获取登陆失败时的提示消息

                    <td class="tdx" colspan="2" style="color:red;text-align: center;">

                        <%= request.getAttribute("msg") == null ? "" : request.getAttribute("msg") %>

                    </td>

        -----------------------------------------------

        3.5.案例: 校验验证码

            -------------------------------------------

            3.4.1.编写ValiImageServlet, 将验证码文本存入session

                request.getSession().setAttribute("valistr", valistr);

            -------------------------------------------

            3.4.2.在处理注册过程中, 从session中取出验证码, 和用户提交过来的进行比较

                if(!valistr1.equalsIgnoreCase(valistr2)){

                    //设置提示消息

                    request.setAttribute("msg", "验证码不正确");

                    //转发回注册页面进行提示

                    request.getRequestDispatcher("/regist.jsp").forward(request, response);

                    return;

                }

       

    ===================================================

    四.Cookie和Session的比较:

        (1) Cookie是将会话中产生的数据保存在客户端, 是客户端的技术

        (2) Session是将会话中产生的数据保存在服务器端, 是服务器端的技术

        (3) Cookie保存的信息的时间比较长, 但是安全性不高. 可能随着用户的操作, Cookie会被清空, 所以Cookie存储数据的稳定性比较差. 因此Cookie适合存放要保存时间较长, 但安全性要求不高的信息

        (4) Session通常保存信息的时间比较有限, 但安全性比较高, 因为是保存在服务器端, 不会随着用户的操作而导致Session意外丢失, 因此session适合存放安全性要求比较高, 但是不需要长时间保存的数据.

    代码实现

    前台表单,将用户输入的信息传入后台LoginServlet,进行表单验证。

    然后LoginServlet将验证完的的信息存入Cookie中,再将Cookie中存储的信息取出进行处理

    <%@page import="java.net.URLDecoder"%>
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML>
    <html>
        <head>
            <meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
            <link rel="stylesheet" href="css/login.css"/>
            <title>EasyMall欢迎您登陆</title>
        </head>
        <body>
            <%
                // 1.获取用户本次请求携带的所有Cookie
                Cookie[] cs=request.getCookies();
                // 2.判断用户是否携带了记住用户名的Cookie
                Cookie findC=null;
                if(cs!=null){
                    for(Cookie c:cs){
                        if("remname".equals(c.getName())){
                            findC=c;//找到了记住用户名的Cookie
                            break;
                        }
                    }
                }
                // 3.如果携带了,获取Cookie中保存的用户名
                String username="";// 用来保存Cookie中携带的用户名
                if(findC != null){
                    // username=findC.getValue(); //%E5%BC%A0%E9%A3%9E
                    username=URLDecoder.decode(findC.getValue(), "utf-8");
                }
                // 4. 将用户名添加到username的input中
            %>
        
            <h1>欢迎登陆EasyMall</h1>
            <form action="/LoginServlet" method="POST">
                <table>
                    <tr>
                        <td colspan="2" style='text-align:center;color:red'><%=request.getAttribute("errMsg")==null?"":request.getAttribute("errMsg")%></td>
                    </tr>
                    <tr>
                        <td class="tdx">用户名:</td>
                        <td><input type="text" name="username" value="<%=username%>"/></td>
                    </tr>
                    <tr>
                        <td class="tdx">&nbsp;&nbsp; 码:</td>
                        <td><input type="password" name="password"/></td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <input type="checkbox" 
                            <%=findC==null?"":"checked='checked'" %>
                            name="remname" value="true"/>记住用户名
                            <input type="checkbox" name="autologin" value="true"/>30天内自动登陆
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2" style="text-align:center">
                            <input type="submit" value="登 陆"/>
                        </td>
                    </tr>
                </table>
            </form>        
        </body>
    </html>
    LoginServlet
    package cn.bingou.web;
    
    import java.io.IOException;
    import java.net.URLEncoder;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import cn.bingou.util.JDBCUtils;
    
    public class LoginServlet extends HttpServlet {
    
        public void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
    
            // 获取web.xml中配置的字符集
            String encode=this.getServletContext().getInitParameter("encode");
            // 1.处理乱码-请求乱码
            // POST请求乱码
            req.setCharacterEncoding(encode);
            // 2.接收请求参数
            String username=req.getParameter("username");// 使用request.getParameter可以获得表单传过来的值 
            String password=req.getParameter("password");
            String remname=req.getParameter("remname");
            // 3.表单验证
                // TODO
            // 4.执行逻辑 
                // 1)记住用户名
                // 判断用户是否勾选了记住用户名
            if(remname != null && "true".equals(remname)){
                // 勾选了记住用户名
                // 创建一个保存用户名的Cookie
                // URLEncoder.encode用来对一个字符串进行编码
                Cookie cookie=new Cookie("rename",URLEncoder.encode(username,encode));
                // 设置一个有效时间
                cookie.setMaxAge(60*60*24*30);
                // 手动设置一个路径 web应用的根路径
                // EasyMall被配置成了虚拟主机的默认web应用
                // 导致req.getContextPath()返回 ""
                // setPath("")-》无效的,所以setPath(""+"/")->有效            
                cookie.setPath(req.getContextPath()+"/");
                // 将Cookie添加到Response中
                resp.addCookie(cookie);
            }else{
                // 如果没有勾选记住用户名-删除之前保存的Cookie
                Cookie cookie=new Cookie("remname","");
                cookie.setPath(req.getContextPath()+"/");
                cookie.setMaxAge(0);// 删除当前Cookie
                resp.addCookie(cookie);
            }
                // 2)登陆
                // 判断用户的用户名和密码是否正确
            String sql="select * from user where username=? and password=?";
            Connection conn=null;
            PreparedStatement ps=null;
            ResultSet rs=null;
            try {
                conn=JDBCUtils.getConnection();
                ps=conn.prepareStatement(sql);
                ps.setString(1, username);
                ps.setString(2, password);
                rs=ps.executeQuery();
                // 5. 根据执行的结果返回应答内容
                if(rs.next()){
                    // 登录成功-向session中添加登录状态
                    req.getSession().setAttribute("user", username);
                    // 重定向到首页
                    resp.sendRedirect(req.getContextPath()+"/index.jsp");
                }else{
                    //添加错误提示信息,并返回login.jsp
                    req.setAttribute("errMsg", "用户名或密码错误");
                    req.getRequestDispatcher("/login.jsp").forward(req, resp);
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("登录出现异常:"+e.getMessage());
            }finally{
                JDBCUtils.close(conn, ps, rs);
            }
        }
    
        public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            doGet(req, resp);
        }
    
    }

    _head.jsp

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <!DOCTYPE HTML>
    <link rel="stylesheet" href="css/head.css"/>
    <meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
    
    <div id="common_head">
        <div id="line1">
            <div id="content">
                <% 
                    HttpSession sess=request.getSession(false);
                    if(sess==null || sess.getAttribute("user")==null){ %>
                        <a href="/login.jsp">登录</a>&nbsp;&nbsp;|&nbsp;&nbsp;
                        <!-- 由于当前项目是虚拟主机的默认web应用,因此项目映射的URL应该是“” -->
                        <!-- <a href="/EasyMall/regist.jsp">注册</a> -->
                        <a href="/regist.jsp">注册</a>    
                <% }else{ %>
                        欢迎 <%=request.getSession().getAttribute("user") %> 回来&nbsp;&nbsp;|&nbsp;&nbsp;
                        <!-- 由于当前项目是虚拟主机的默认web应用,因此项目映射的URL应该是“” -->
                        <!-- <a href="/EasyMall/regist.jsp">注册</a> -->
                        <a href="/LogoutServlet">注销</a>
                <% }%>
                <a href="/login.jsp">登录</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="/regist.jsp">注册</a>
            </div>
        </div>
        <div id="line2">
            <img id="logo" src="img/head/logo.jpg"/>
            <input type="text" name=""/>
            <input type="button" value="搜 索"/>
            <span id="goto">
                <a id="goto_order" href="#">我的订单</a>
                <a id="goto_cart" href="#">我的购物车</a>
            </span>
            <img id="erwm" src="img/head/qr.jpg"/>
        </div>
        <div id="line3">
            <div id="content">
                <ul>
                    <li><a href="#">首页</a></li>
                    <li><a href="#">全部商品</a></li>
                    <li><a href="#">手机数码</a></li>
                    <li><a href="#">电脑平板</a></li>
                    <li><a href="#">家用电器</a></li>
                    <li><a href="#">汽车用品</a></li>
                    <li><a href="#">食品饮料</a></li>
                    <li><a href="#">图书杂志</a></li>
                    <li><a href="#">服装服饰</a></li>
                    <li><a href="#">理财产品</a></li>
                </ul>
            </div>
        </div>
    </div>
  • 相关阅读:
    两句话的区别在于目录的不同。
    关于系统的操作全在这里了。这个看起来很重要。
    屏幕坐标的方法
    改变轴心的操作。
    关于旋转的变换处理方法。
    对其位置
    点边同事移除的办法处理。
    移动的坐标变换
    判断文件是否存在的函数。
    把节点归零处理
  • 原文地址:https://www.cnblogs.com/chuijingjing/p/9746347.html
Copyright © 2011-2022 走看看