该方法用于添加 cookie 对象,用来保存客户端的用户信息。
语法:
参数说明:
向 cookie 对象中添加信息,关键代码如下:
- <%
- Cookie cookie = new Cookie("user","lzw");
- response.addCookie(cookie);
- %>
本示例使用 addCookie 方法将信息保存在 cookie 对象中,并获取 cookie 中信息输出在页面中,运行结果如图所示。
本示例关键代码如下:
- <body>
- <%
- request.setCharacterEncoding("GBK");
- String name = request.getParameter("name");//获取页面中提交的表单信息
- String hobby = request.getParameter("hobby");
- Cookie cookies[] = request.getCookies();//获取cookie对象
- if(cookies!=null){//判断cookie对象是否为空
- for(int i=0;i<cookies.length;i++){
- if(cookies[i].getName().equals("name")){//判断指定对象是否为空
- name = cookies[i].getValue();
- }
- }
- }else if(name!=null){
- Cookie c = new Cookie("name",name);//创建cookie对象
- c.setMaxAge(50);
- response.addCookie(c);
- }
- if(cookies!=null){
- for(int i=0;i<cookies.length;i++){
- if(cookies[i].getName().equals("hobby"))
- hobby=cookies[i].getValue();
- }
- }else if(name!=null){
- Cookie c=new Cookie("hobby",hobby);
- response.addCookie(c);//添加cookie对象
- }
- %>
- <p>保存数据到cookie的测试</p>
- <form action="index.jsp" method="post">
- 姓名:<input type="text" name="name" value="<%if(name!=null)out.println(name);
- %>"><%--如果cookie中保存了相关信息,在页面中显示--%>
- 兴趣:<input type="text" name="hobby" value="<%if(hobby!=null)out.println(hobby);%>">
- <input type="submit" value="保存">
- </form>
- 你的名字是:<%if(name!=null)out.println(name);%>
- 你的兴趣是:<%if(hobby!=null)out.print(hobby);%>
- </body>