• JavaWeb学习 第6章 Servlet和Cookie


    1.什么是 Cookie?

    Cookie 实际上就是用户通过浏览器访问网站时,Web服务器在用户的硬盘上写入的一个文本文件

    它包含了用户的某些信息,它是以键值对的形式存储的

    cookie1

    2. 使用到了 Cookie 的典型应用

    下面这些都采用了  Cookie 技术,都是我们经常看到的

    c1

    c2

    c3

     
    3. Cookie 编程

    setPath 就是设置保存的位置

    cookie2

     
    Cookie 的构造方法的参数有两个,都是 String 类型的,前面是 “键”,后面是“值”

    cookie3

    setMaxAge 设置有效期, getMaxAge 得到有效期

    cookie5

    response.add(...) 发送,也就是保存 Cookie 对象

    cookie3

    读取 request.getCookies()

    cookie6

    cookie.setValue()

    cookie7

    4.  Cookie的 缺陷

    cookie8

    5. 编程实例

    前台  cookieInput.htm

    <html>
    
    <head>
    
    <title>cookie input page</title>
    
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
    </head>
    
    <body>
    
    请输入用户名(英文或者数字)
    
    <br>
    
    <form name="form1" action="/webproject3/servlet/setCookies"
    
    method="post">
    
    <table border="0">
    
    <tr>
    
    <td>
    
    用户名:
    
    </td>
    
    <td>
    
    <input type="text" name="username">
    
    </td>
    
    </tr>
    
    <tr>
    
    <td colspan="2" align="center">
    
    <input name="submit" value="submit" type="submit">
    
    </td>
    
    </tr>
    
    </table>
    
    </form>
    
    </body>
    
    </html>
    

      

    后台 

    字符串处理类

    package webbook.util;
    
    public class StringUtil {
    
    	/**
    	 * 
    	 * 判断输入的字符串参数是否为空。
    	 * @param args 输入的字串
    	 * @return true/false
    	 */
    
    	public static boolean validateNull(String args) {
    		if (args == null || args.length() == 0) {
    			return true;
    		} else {
    			return false;
    		}
    	}
    
    	/**
    	 * 
    	 * 判断输入的字符串参数是否为空或者是"null"字符,如果是,就返回target参数,如果不是,就返回source参数。
    	 */
    
    	public static String chanageNull(String source, String target) {
    		if (source == null || source.length() == 0 || source.equalsIgnoreCase("null")) {
    			return target;
    		} else {
    			return source;
    		}
    	}
    
    	/**
    	 * 
    	 * 过滤<, >,\n 字符的方法。	 
    	 * @param input 需要过滤的字符	
    	 * @return 完成过滤以后的字符串
    	 */
    
    	public static String filterHtml(String input) {
    		if (input == null) {
    			return null;
    		}
    		if (input.length() == 0) {
    			return input;
    		}
    		input = input.replaceAll("&", "&");
    		input = input.replaceAll("<", "<");
    		input = input.replaceAll(">", ">");
    		input = input.replaceAll(" ", " ");
    		input = input.replaceAll("'", "'");
    		input = input.replaceAll("\"", """);
    		return input.replaceAll("\n", "<br>");
    
    	}
    
    }
    

      

    设置 Cookie 的Servlet

    package webbook.chapter6;
    
    import java.io.IOException;
    
    import java.io.PrintWriter;
    
    import java.text.SimpleDateFormat;
    
    import java.util.Date;
    
    import webbook.util.StringUtil;
    
    import javax.servlet.ServletException;
    
    import javax.servlet.http.Cookie;
    
    import javax.servlet.http.HttpServlet;
    
    import javax.servlet.http.HttpServletRequest;
    
    import javax.servlet.http.HttpServletResponse;
    
    public class SetCookiesServlet extends HttpServlet {
    
    	private static final long serialVersionUID = 4400760543502956525L;
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    		doPost(request, response);
    
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    		String output = null;
    
    		String username = request.getParameter("username");
    
    		if (!StringUtil.validateNull(username)) {
    
    			Cookie cookie1 = new Cookie("username", StringUtil.filterHtml(username));
    
    			// cookie的有效期为1个月
    
    			cookie1.setMaxAge(24 * 60 * 60 * 30);
    
    			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    
    			Cookie cookie2 = new Cookie("lastTime", sdf.format(new Date()));
    
    			cookie2.setMaxAge(24 * 60 * 60 * 30);
    
    			response.addCookie(cookie1);
    
    			response.addCookie(cookie2);
    
    			output = "本次登录时间与用户名已经写到Cookie中。<br><a href=\"/webproject3/servlet/getCookies \">查看Cookies</a>";
    
    		} else {
    
    			output = "用户名为空,请重新输入。<br><a herf=\"/webproject3/cookieInput.htm\">输入用户名</a>";
    
    		}
    
    		response.setContentType("text/html;charset=UTF-8");
    
    		PrintWriter out = response.getWriter();
    
    		out.println("<html>");
    
    		out.println("<head><title>set cookies </title></head>");
    
    		out.println("<body>");
    
    		out.println("<h2>" + output + "</h2>");
    
    		out.println("</body>");
    
    		out.println("</html>");
    
    		out.flush();
    
    		out.close();
    
    	}
    
    }
    

      

    得到 Cookie 的 Servlet

    package webbook.chapter6;
    
    import java.io.IOException;
    
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    
    import javax.servlet.http.Cookie;
    
    import javax.servlet.http.HttpServlet;
    
    import javax.servlet.http.HttpServletRequest;
    
    import javax.servlet.http.HttpServletResponse;
    
    public class GetCookiesServlet extends HttpServlet {
    
    	private static final long serialVersionUID = 4400760543502956525L;
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    		doPost(request, response);
    
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    		response.setContentType("text/html;charset=UTF-8");
    
    		PrintWriter out = response.getWriter();
    
    		out.println("<html>");
    
    		out.println("<head><title>display login infomation</title></head>");
    
    		out.println("<body>");
    
    		out.println("<h2>从Cookie中获得上次登录时间与用户名</h2>");
    
    		Cookie[] cookies = request.getCookies();
    
    		Cookie cookie = null;
    
    		for (int i = 0; i < cookies.length; i++) {
    
    			cookie = cookies[i];
    
    			if (cookie.getName().equals("username")) {
    
    				out.println("用户名:" + cookie.getValue());
    
    				out.println("<br>");
    
    			}
    
    			if (cookie.getName().equals("lastTime")) {
    
    				out.println("上次登录时间:" + cookie.getValue());
    
    				out.println("<br>");
    
    			}
    
    		}
    
    		out.println("</body>");
    
    		out.println("</html>");
    
    		out.flush();
    
    		out.close();
    
    	}
    
    }
    

      

    测试结果:

    1

    2

    3

  • 相关阅读:
    【PASOTTIPASOTTI 伞】PASOTTI黑色聚酯纤维伞 Style 478
    乐雨 德国happyrain 超大男士高尔夫伞 直柄伞 双人伞 双层伞面防风雨伞 黑色【图片 价格 品牌 报价】-京东
    Larmes琅幕仕家居马头长款短柄自动雨伞 晴雨两用太阳伞防紫外线遮阳男士商务伞 雨伞雨具 骏马长款-金色配饰【图片 价格 品牌 报价】-京东
    Planner – 项目管理软件
    Project Server 2010安装部署手册(1.5版)
    Serena Software :: pod-update
    ]project-open[ 中国 功能一览
    几块钱或许能治好你的白发(2)
    爱心日式便当 给爸爸妈妈的爱心便当
    给老公做的爱心便当,持续更新!-西餐-19楼私房菜-杭州19楼
  • 原文地址:https://www.cnblogs.com/yinger/p/2122405.html
Copyright © 2020-2023  润新知