JSP Response. Addcookie() method: add cookie object

addCookie(Cookie cookie)

Example

<%
  Cookie cookie = new Cookie("user","lzw");
  response.addCookie(cookie);
%>

Typical application

<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>
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>