Using Session in Servlet/JSP

Categories: Java; Tagged with: ; @ July 3rd, 2012 0:03

Using session in Servlet:

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().write("Servlet HelloWorld!");
		
		HttpSession session = request.getSession(false);
		if(session == null) {
			response.sendRedirect("ServletLogin");
			return;
		}else {
			System.out.println(session.getId());
			Integer totalAccess = (Integer) session.getAttribute("totalAccess"); // Get session attribute;
			if(totalAccess == null) {
				totalAccess = 0;
			}
			
			totalAccess += 1;
			session.setAttribute("totalAccess", totalAccess); // set attribute
			
			response.getWriter().write("TotalAccess: " + session.getAttribute("totalAccess"));
		}

 

Using session in JSP:

Jsp page directive:

<%@ page
          [ language=”java” ]
          [ extends=”package.class” ]
          [ import=”{package.class | package.*}, …” ]
          [ session=”true | false” ]
          [ buffer=”none | 8kb | sizekb” ]
          [ autoFlush=”true | false” ]
          [ isThreadSafe=”true | false” ]
          [ info=”text” ]
          [ errorPage=”relativeURL” ]
          [ contentType=”mimeType [ ;charset=characterSet ]”   |   “text/html ; charset=ISO-8859-1” ]
          [ isErrorPage=”true | false” ]
%>

“session = true” by default.  when access “session”, if session is not existing, will create one by default.
we can set:

<%-- Prevent the creation of a session –%>
<%@ page session="false">

to prevent the Creation of a Session in a JSP Page.

 

We didn’t mention about the thread safe of session, here is a post from IBM DW:
http://www.ibm.com/developerworks/library/j-jtp09238/index.html



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.