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

    • 设置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  ;
    	%>
    	<%	
    		boolean flag = false;
    		Cookie[] cookies = request.getCookies() ;
    		for(Cookie cookie :cookies){
    			if(cookie.getName().equals("uname")){
    				uname = cookie.getValue() ;
    				flag = true;
    			}
    		}
    		//判断cookie是否生效
    		if(!flag){
    			out.print("cookie已经失效");
    		}
    		else{
    			out.print("cookie:"+uname);
    		}
    	%>
    
    
    	<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的有效时间,单位为秒
    			cookie.setMaxAge(10);
    			
    			//服务端增加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
    在这里插入图片描述
    初次访问没有设置cookie时显示为失效

    填上信息后再次访问
    在这里插入图片描述
    过十秒钟再次访问:
    在这里插入图片描述

  • 相关阅读:
    聊聊什么是慢查、如何监控?如何排查?
    navicat连接sqlserver数据库提示:未发现数据源名并且未指定默认驱动程序
    定位元素的父(parent::)、兄弟(following-sibling::、preceding-sibling::)节点
    java方法返回值前面的泛型是什么?
    java8Lambda的环绕执行模式
    try语法糖
    php-fpm优化内存占用大
    Gitlab安装
    第2章 python入门
    LAMP源码安装
  • 原文地址:https://www.cnblogs.com/xdr630/p/15255109.html
Copyright © 2011-2022 走看看