zoukankan      html  css  js  c++  java
  • jsp课程笔记之cookie案例(一)

    1. 使用Cookie实现 记住用户名 功能
      建议 cookie只保存 英文数字,否则需要进行编码、解码
      在这里插入图片描述
      login.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    	<%!
    		String uname  ;
    	%>
    	<%
    		Cookie[] cookies = request.getCookies() ;
    		for(Cookie cookie :cookies){
    			if(cookie.getName().equals("uname")){
    				uname = cookie.getValue() ;
    			}
    		}
    		
    	%>
    
    
    	<form action="check.jsp" method="post">
    		用户名:<input type="text" name="uname"  value="<%=(uname==null?"":uname)%>"><br/>
    		
    		
    		密码:<input type="password" name="upwd"><br/>
    		<input type="submit" value="登陆"><br/>
    		
    	</form>
    </body>
    </html>
    

    check.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    		<%
    			request.setCharacterEncoding("utf-8") ;
    			String name = request.getParameter("uname");
    			String pwd = request.getParameter("upwd");
    			
    			//将用户名 加入到Cookie中
    			Cookie cookie = new Cookie("uname",name);
    						
    			//服务端增加cookie
    			response.addCookie(cookie) ;
    			
    			//服务端给客户端响应将cookie给客户端,转发或重定向都可以
    			response.sendRedirect("A.jsp") ;
    		
    		%>
    </body>
    </html>
    

    A.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    
    </body>
    </html>
    

    访问:http://localhost:8080/01_jsp/cookieDemo/login.jsp
    在这里插入图片描述
    出现null,这是因为还没有从客户端发送请求给服务端。
    输入:
    在这里插入图片描述
    跳转到A.jsp
    在这里插入图片描述
    再次回到login.jsp,发现用户名自动为zs,这就是cookie在login.jsp和A.jsp两者保留了用户名,共享
    在这里插入图片描述

  • 相关阅读:
    Linux 系统中 sudo 命令的 10 个技巧
    如何在 Linux 中配置基于密钥认证的 SSH
    选择 NoSQL 数据库需要考虑的 10 个问题
    10 个 Linux 中方便的 Bash 别名
    扒一扒 EventServiceProvider 源代码
    [Binary Hacking] ABI and EABI
    瀑布流 ajax 预载入 json
    PHP5+标准函数库观察者之实现
    使用汇编分析c代码的内存分布
    but no declaration can be found for element &#39;aop:aspectj-autoproxy&#39;.
  • 原文地址:https://www.cnblogs.com/xdr630/p/15255110.html
Copyright © 2011-2022 走看看