zoukankan      html  css  js  c++  java
  • 小甜点

    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>
  • 相关阅读:
    WP7编译问题:The application could not be launched for debugging
    cocos2dxnaTweeJump学习笔记1(都是自己看别人代码后所感所想,希望有懂的人指出我的错误或者大家交流交流)
    判断datatalbe是否为空
    SOAP协议基础(转自Ksxs's )
    那些年我还不懂:IList,ICollection,IEnumerable,IEnumerator,IQueryable(转)
    MyEclipse中 智能提示 JSP 页面的html 标记属性值
    MyEclipse中设置智能提示
    MyEclipse快捷键大全
    向朋友借钱:文章值得一读,让人思索良久
    生存逼着我成功
  • 原文地址:https://www.cnblogs.com/sflik/p/4574403.html
Copyright © 2011-2022 走看看