Javaweb_Servlet_Session
Session-Server side(store info in server, server created the session)
server(tomcat) will create a session to each client(browser), one session with one browser.
1 //中文乱码问题,英文环境不需要考虑该情况. 2 req.setCharacterEncoding("utf-8"); 3 resp.setCharacterEncoding("utf-8"); 4 resp.setContentType("text/html;charset=utf-8"); 5 //get session 6 HttpSession session = req.getSession(); 7 session.setAttribute("name", "Mingyue");//set value to session 8 String sessionId = session.getId();//get session id 9 //to know whether the session is new or not 10 if (session.isNew()) { 11 resp.getWriter().write("created a session, ID = " + sessionId); 12 } else { 13 resp.getWriter().write("session existed in the server and ID = " + sessionId); 14 } 15 //what happened when session created 16 // Cookie cookie = new Cookie("JSESSIONID", sessionId); 17 // resp.addCookie(cookie);
get attribute of session.
1 HttpSession session = req.getSession(); 2 String name = (String) session.getAttribute("name");//get 3 resp.getWriter().write(name); 4 System.out.println(name);
remove attribute and invalidate session.
1 HttpSession session = req.getSession(); 2 session.removeAttribute("name"); 3 session.invalidate();
set attribute as an object and get attibute of it.
1 session.setAttribute("name",new Person("Mingyue",1));//set an object in session 2 Object name = session.getAttribute("name"); 3 resp.getWriter().write(name.toString()); 4 System.out.println(name.toString());
configure session time in xml.
1 <session-config> 2 <!--expired in 15 min--> 3 <session-timeout>15</session-timeout> 4 </session-config>

浙公网安备 33010602011771号