现在的位置: 首页 > 综合 > 正文

JavaWeb学习 第6章 Servlet和Cookie

2012年03月26日 ⁄ 综合 ⁄ 共 4443字 ⁄ 字号 评论关闭

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

抱歉!评论已关闭.