我写了个小程序,为了用cookie传递数据,即html页面访问servlet1时,servlet1给一个cookie,当html访问servlet2时获取cookie的值,但抛出了异常?
HTML代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>MyHtml.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<body>
This is my HTML page. <br>
<a href="/CookieDemo/servlet/CookieDemo2?name=电视机">电视机</a>
<a href="/CookieDemo/servlet/CookieDemo2?name=电冰箱">电冰箱</a>
<a href="/CookieDemo/servlet/CookieDemo2?name=微波炉">微波炉</a><br/>
<form action="/CookieDemo/servlet/CookieDemo3">
<input type="submit" value="结账" />
</form>
</body>
</html>
servlet1代码:
public class CookieDemo2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//接受html请求过来的参数数据
String name = request.getParameter("name");
//将数据进行先编码在解码过程,解决乱码
name = new String(name.getBytes("iso8859-1"),"utf-8");
response.getWriter().write("您选择了商品"+name);
//创建Cookie将购买的商品以cookie的形式返回给浏览器
Cookie cookie = new Cookie("name",name);
//设置cookie保存的 时间,此处设置成5分钟
cookie.setMaxAge(1*60*5);
//将cookie回写给浏览器
response.addCookie(cookie);
//提供超链接,返回购买页
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
response.getWriter().write("<a href='/CookieDemo/MyHtml.html'>返回继续购买</a>");
}
servlet2代码:
public class CookieDemo3 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
response.getWriter().write("您购买的商品是:");
Cookie[] names = request.getCookies();
for(int i=0;names!=null&&i<names.length;i++){
if(names[i].getName().equals("name")){
String value = names[i].getValue();
response.getWriter().write(value);
}
}
}
|