• 小甜点


    cookie客户端(浏览器)缓存,可以保存用户的登陆信息,浏览信息等

    用户请求服务器(tomcat),服务器响应时会在响应头里面添加cookie,下次再访问服务器时,会把cookie带上,服务器(这里的服务器一般指的是jsp,jsp前身就是servlet)就可以获取你的cookie信息

    打个比喻:去某餐厅吃饭,你点完餐后,服务员会给你个写着号码的纸条,你再去领餐时,就会带上纸条,服务员就会知道你点的餐。

    举个栗子:用户填写登陆信息后,提交给服务器,服务器得到用户的登陆(请求)信息,判断密码是否正确,如果正确,把用户名保存到cookie中,下次再登陆(请求)的时候会直接获取到cookie中的用户名

    servlet代码:

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("utf-8");//post请求编码问题
            response.setContentType("text/html;charset=utf-8");//响应编码问题 
            String username = request.getParameter("username");
            String password = request.getParameter("password");
    if(username.equals("张三") && password.equals("123456")) { // 保存错误信息到request域中,转发到login.jsp request.setAttribute("msg", "用户名或密码错误!"); // 添加一句,把当前用户名保存到request域中,方便表单回显数据 request.setAttribute("username", username); request.getRequestDispatcher("/login.jsp").forward(request, response); } else { Cookie cookie = new Cookie("username", URLEncoder.encode(username, "UTF-8"));//因为cookie不能包含中文,
    所以要用到
    URLEncoder.encode()方法进行url编码
    cookie.setMaxAge(60*60);//设置cookie过期时间
    response.addCookie(cookie);
    // 重定向到home.jsp
    response.sendRedirect(request.getContextPath() + "/home.jsp"); } }

    jsp代码:

      <body>
    <h1>登录</h1>
    <p style="color:red; font-weight: 900;">
    <%
        String msg = (String)request.getAttribute("msg");
        if(msg != null) {
            out.print(msg);
        }
    /*
        获取登录时保存的Cookie,获取其中用户名,赋值给username
    */
        String username = "";
        Cookie[] cs = request.getCookies();
        if(cs != null) {
            for(Cookie c : cs) {
                if(c.getName().equals("username")) {
                    username = URLDecoder.decode(c.getValue(), "UTF-8");//这里使用URLDecoder.decode()方法进行url解码
                }
            }    
        }
    %>
    </p>
    <form action="<%=request.getContextPath()%>/LoginServlet" method="post">
    用户名:<input type="text" name="username" value="<%=username%>"/><br/>
    密 码:<input type="password" name="password"/><br/>
    <input type="submit" value="登录"/>
    </form>
      </body>
  • 相关阅读:
    098实战 Job的调度
    maven在windows下的安装
    Map的知识点梳理(不包含collections工具类)
    001 LRU-缓存淘汰算法
    Android渲染机制和丢帧分析
    Android性能优化典范
    正确使用Android性能分析工具——TraceView
    android View 绘制完成监听
    那些年我们用过的显示性能指标
    view, surfaceView, invalidate, postInvalidate, 刷新屏幕
  • 原文地址:https://www.cnblogs.com/sflik/p/4574403.html
Copyright © 2020-2023  润新知