📄 sessionservlet.java
字号:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Chapter 10, Listing 5
public class SessionServlet extends HttpServlet
{
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws IOException
{
// Set the content type of the response
res.setContentType("text/html");
// Get output stream and writers
OutputStream out = res.getOutputStream();
PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( out ) );
// Determine whether an existing session exists
HttpSession session = req.getSession(false);
// If no existing session, add a visit value of one to a new session
if(session == null)
{
session=req.getSession(true);
session.putValue ("VisitCount", "1");
}
pw.println("<html><body><pre>");
pw.println("session.isNew()="+session.isNew());
pw.println("session.getCreationTime()="+ new java.util.Date( session.getCreationTime()));
pw.println("session.getID()="+session.getId());
pw.println("session.getLastAccessedTime()=" + new java.util.Date(session.getLastAccessedTime()));
// Modify a session variable, so state information is changed from one invocation
// to another of this servlet
String strCount = (String) session.getValue("VisitCount");
pw.println("No. of times visited = " + strCount);
// Increment counter
int count = Integer.parseInt(strCount); count++;
// Place new session data back for next servlet invocation
session.putValue("VisitCount", Integer.toString(count));
pw.println ("</pre></body></html>");
pw.flush();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -