以下是Cookie的完整实例
MyEclipse新建web Project工程,建两个jsp文件,如下
1、login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); if("POST".equals(request.getMethod())){ Cookie usernameCookie=new Cookie("username",request.getParameter("username"));//新建名为username的Cookie Cookie visittimesCookie=new Cookie("visitTimes","0"); //新建Cookie response.addCookie(usernameCookie);//添加到response中 response.addCookie(visittimesCookie);//response会将Cookie发送给客户端 response.sendRedirect(request.getContextPath()+"/cookie.jsp");//显示Cookie页面 return; } %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>请先登录</title> <link rel="stylesheet" type="text/css" href="css/style.css"> </head> <body> <div align="center" style="margin:10px; "> <fieldset> <legend>登录</legend> <form action="login.jsp" method="post"> <table> <tr> <td>帐号:</td> <td> <input type="text" name="username" style="width:200px; "> </td> </tr> <tr> <td>密码:</td> <td> <input type="password" name="password" style="width:200px; "> </td> </tr> <tr> <td> </td> <td> <input type="submit" value=" 登 录 " class="button"> </td> </tr> </table> </form> </fieldset> </div> </body> </html>
2、cookie.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" errorPage="login.jsp" %> <% request.setCharacterEncoding("UTF-8"); String username=""; //用户名 int visitTimes=0; //访问次数 Cookie[] cookies=request.getCookies();//所有的Cookie for(int i=0;i<cookies.length;i++){ Cookie cookie=cookies[i]; //第i个Cookie if("username".equals(cookie.getName())){ username=cookie.getValue(); } else if("visitTimes".equals(cookie.getName())){ visitTimes=Integer.parseInt(cookie.getValue()); } } if(username==null||username.trim().equals("")){ throw new Exception("还没登陆,请先登录"); } Cookie visitTimesCookie=new Cookie("visitTimes",Integer.toString(++visitTimes)); response.addCookie(visitTimesCookie);//覆盖名为visitTimes的Cookie %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <div align="center" style="margin:10px;"> <fieldset> <legend>登录信息</legend> <form action="login.jsp" method="post"> <table> <tr> <td>你的账号:</td> <td><%=username %></td> </tr> <tr> <td>登陆次数:</td> <td><%=visitTimes %></td> </tr> <tr> <td></td> <td> <input type="button" value="刷新" onclick="location='<%= request.getRequestURI() %>?ts='+new Date().getTime();" class="button"> </td> </tr> </table> </form> </fieldset> </div> </body> </html>
效果:
随便输入账号和密码,点击登录