Cookies操作
Cookies是指在Web应用中,为了辨别用户身份而存储在用户本地计算机上的数据。Servlet API提供了Cookie操作类,封装了操作Cookies常用方法。
代码:
package com.foxmail.xxy668;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Cookies extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("gb2312");
PrintWriter out=response.getWriter();
Cookie cookie=new Cookie("name","Gates");
//cookie.setMaxAge(622080000);
response.addCookie(cookie);
Cookie[] cookies=request.getCookies();
if(cookies!=null){
out.print("<font size='2'>");
out.print("follows in the passage is the content of Cookie:<br>");
for(int i=0;i<cookies.length;i++){
Cookie c=cookies[i];
String name=c.getName();
String value=c.getValue();
out.println(name+"="+value+"<br>");
}
out.print("</font>");
}else{
out.print("not luck!");
}
}
}
代码解析:
1、第17行创建了一个Cookie对象,这个Cookie的名字叫做name,存储的信息为Gates
2、第19行把这个Cookie写入到用户本地的计算机中。
3、第21行取出用户计算机中的Cookie
4、第23行到29行将Cookie内容打印到页面中。
Session操作
在JSP中有内置的Session对象,可以用来保持服务器与用户之间的会话状态,在Servlet中同样可以对Session进行方便地操作。
代码:
package com.foxmail.xxy668;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Sessions extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("gb2312");
PrintWriter out=response.getWriter();
HttpSession session=request.getSession(true);
out.println("<font size='2'>");
Date created=new Date(session.getCreationTime());
Date accessed=new Date(session.getLastAccessedTime());
out.println("the ID of the Session is:"+session.getId()+"<br>");
out.println("the date of the create session is:"+created+"<br>");
out.println("the last vist time is :"+accessed+"<br>");
session.setAttribute("msg","Hello");
Enumeration e=session.getAttributeNames();
out.println("the content of session is");
while(e.hasMoreElements()){
String name=(String)e.nextElement();
String value=session.getAttribute(name).toString();
out.println(name+"="+value+"<br>");
}
out.println("</font>");
}
}
代码解析:
1、第17行从request对象中取出当前Session对象。
2、第21行到第23行先后依次取出Session的创建时间、上次被访问时间、Session的id。
3、第25行在Session中设置了一个名为msg的属性变量,值为Hello
4、第27行取出Session的所有属性并放到一个集合当中。
5、第29行到第33行通过循环将Session中的内容打印在页面。
在上面的例子中,可以看出只要不关闭浏览器,在整个用户与服务器的交互期间,这个Session对象是始终存在的,这一点可以从Session的id和创建时间看出。一旦关闭浏览器,这个Session对象就会被销毁,再次访问的时候
Cookie和Session在使用中基本上是相似的,唯一不同的地方是声明周期的不同,Cookie的生存周期是代码控制,而Session的声明周期是从会话开始直到会话结束。了解了这一点这两个操作可以当成一个操作来理解使用。