会话 httpSession

package session_demo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(urlPatterns="/session.do")
public class session01 extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1183874912372297181L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		HttpSession session=req.getSession();
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out=resp.getWriter();
		if(session.isNew()){
			out.println("新建的会话,ID是:"+session.getId()+"<br/>");
			out.println("新建的会话,创建时间是:"+session.getCreationTime()+"<br/>");
		}else{
			out.println("会话已经存在,ID是:"+session.getId()+"<br/>");
			out.println("会话已经存在,创建时间是:"+session.getCreationTime()+"<br/>");
		}
		out.println("最后一次访问会话的时间是:"+session.getLastAccessedTime()+"<br/>");
		out.println("会话的有效时间是:"+session.getMaxInactiveInterval()+"<br/>");
		session.setAttribute("name", "刘进");
		
		//session.invalidate();
		session.setMaxInactiveInterval(3);
	}

}
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	
  </head>
  
  <body>
    <%=session.getAttribute("name") %>
  </body>
</html>


你可能感兴趣的:(会话 httpSession)