Handling Session in
Servlets
Agenda
• Implementing session tracking from scratch
• Using basic session tracking
• Understanding Session tracking api
• URLEncoding
• Tracking user counts
Session Management
• Different ways to manage Sessions
- Using Cookie(discussed in prev chapter)
- Using HttpSession Object
- Using URL Rewriting
- Using HiddenFields
Session Management
• Cookie is the default method of handling session in JEE
• If the client browser does not support cookie creation then the URL
rewriting is the only option
Hidden Fields
• A webserver can send hidden HTML form fields
- <input type=“hidden” name=“sessionid” value=‘123”>
• When form submitted the value will be send to the Server
• But hyperlink does not result in form submission
• Generally not used for Session Tracking
URL Rewriting
• We can append some extra data at the end of each URL that
identifies the session
- http://www.talentedge.in/file.jsp;sessionid=123
• URL rewriting is better alternate for client that do not support
cookies
• Must encode all URL
• All pages must be dynamically generated(JSP)
URL Rewriting? how
• Session tracking code:
- No change
• Code that generates hypertext links back to same site:
- Pass URL through response.encodeURL.
• If server is using cookies, this returns URL unchanged
• If server is using URL rewriting, this appends the session info to
the URL
• E.g.:
- String url = "order-page.html";
- url = response.encodeURL(url);
• Code that does sendRedirect to own site:
- Pass URL through response.encodeRedirectURL
HttpSession
• Servlet api provides HttpSession Object
- Request.getSession()
• This will return the current session existing with this request.
• If no session exists then create a new one
- request.getSession(true)
• Same as request.getSession()
- Request.getSession(false)
• This will return the current session existing with this request
• If no session exits then it will return null
HttpSession (cont)
• Access the session object
- Call request.getSession to get HttpSession object
- This is a hashtable associated with the user
• Look up information associated with a session.
- Call getAttribute on the HttpSession object, cast the return value to the
appropriate type, and check whether the result is null.
• Store information in a session.
- Use setAttribute with a key and a value.
• Discard session data.
- Call removeAttribute discards a specific value.
- Call invalidate to discard an entire session.
HttpSession Methods(Cont)
• isNew
- Determines if session is new to client (not to page)
• getCreationTime
- Returns time at which session was first created
• getLastAccessedTime
- Returns time at which session was last sent from client
• getMaxInactiveInterval , setMaxInactiveInterval
- Gets or sets the amount of time session should go without access before
being invalidated
• Invalidate
- Invalidates current session
HttpSession Methods
• getAttribute
- Extracts a previously stored value from a session object.
- Returns null if no value is associated with given nam
• setAttribute
- Associates a value with a name. Monitor changes: values
implement HttpSessionBindingListener
• removeAttribute
- Removes values associated with name.
• getAttributeNames
- Returns names of all attributes in the session.
• getId
Returns the unique identifier.
Tracking access count
public class ShowSession extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
HttpSession session = request.getSession();
String heading;
Integer accessCount = (Integer)session.getAttribute("accessCount");
if (accessCount == null) {
accessCount = new Integer(0);
heading = "Welcome, Newcomer";
} else {
heading = "Welcome Back";
accessCount = new Integer(accessCount.intValue() + 1);
}
session.setAttribute("accessCount", accessCount);
Tracking access count
PrintWriter out = response.getWriter();
out.println
(docType +"<HTML>n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>n" +
"<BODY BGCOLOR="#FDF5E6">n" +
"<CENTER>n" +
"<H1>" + heading + "</H1>n" +
"<H2>Information on Your Session:</H2>n" +
"<TABLE BORDER=1>n" +
"<TR BGCOLOR="#FFAD00">n" +
" <TH>Info Type<TH>Valuen" +
" <TD>Number of Previous Accessesn" +
" <TD>" + accessCount + "n" +
"</TABLE>n" +
"</CENTER></BODY></HTML>");
Summary
• Sessions do not travel across network
- Only unique identifier does
• Get the session
- request.getSession
• Extract data from session
- session.getAttribute
• Do typecast and check for null
• If you cast to a generic type, use @SuppressWarnings
Summary
• Put data in session
- session.setAttribute
• Custom classes in sessions
- Should implement Serializable

Advance java session 8

  • 1.
  • 2.
    Agenda • Implementing sessiontracking from scratch • Using basic session tracking • Understanding Session tracking api • URLEncoding • Tracking user counts
  • 3.
    Session Management • Differentways to manage Sessions - Using Cookie(discussed in prev chapter) - Using HttpSession Object - Using URL Rewriting - Using HiddenFields
  • 4.
    Session Management • Cookieis the default method of handling session in JEE • If the client browser does not support cookie creation then the URL rewriting is the only option
  • 5.
    Hidden Fields • Awebserver can send hidden HTML form fields - <input type=“hidden” name=“sessionid” value=‘123”> • When form submitted the value will be send to the Server • But hyperlink does not result in form submission • Generally not used for Session Tracking
  • 6.
    URL Rewriting • Wecan append some extra data at the end of each URL that identifies the session - http://www.talentedge.in/file.jsp;sessionid=123 • URL rewriting is better alternate for client that do not support cookies • Must encode all URL • All pages must be dynamically generated(JSP)
  • 7.
    URL Rewriting? how •Session tracking code: - No change • Code that generates hypertext links back to same site: - Pass URL through response.encodeURL. • If server is using cookies, this returns URL unchanged • If server is using URL rewriting, this appends the session info to the URL • E.g.: - String url = "order-page.html"; - url = response.encodeURL(url); • Code that does sendRedirect to own site: - Pass URL through response.encodeRedirectURL
  • 8.
    HttpSession • Servlet apiprovides HttpSession Object - Request.getSession() • This will return the current session existing with this request. • If no session exists then create a new one - request.getSession(true) • Same as request.getSession() - Request.getSession(false) • This will return the current session existing with this request • If no session exits then it will return null
  • 9.
    HttpSession (cont) • Accessthe session object - Call request.getSession to get HttpSession object - This is a hashtable associated with the user • Look up information associated with a session. - Call getAttribute on the HttpSession object, cast the return value to the appropriate type, and check whether the result is null. • Store information in a session. - Use setAttribute with a key and a value. • Discard session data. - Call removeAttribute discards a specific value. - Call invalidate to discard an entire session.
  • 10.
    HttpSession Methods(Cont) • isNew -Determines if session is new to client (not to page) • getCreationTime - Returns time at which session was first created • getLastAccessedTime - Returns time at which session was last sent from client • getMaxInactiveInterval , setMaxInactiveInterval - Gets or sets the amount of time session should go without access before being invalidated • Invalidate - Invalidates current session
  • 11.
    HttpSession Methods • getAttribute -Extracts a previously stored value from a session object. - Returns null if no value is associated with given nam • setAttribute - Associates a value with a name. Monitor changes: values implement HttpSessionBindingListener • removeAttribute - Removes values associated with name. • getAttributeNames - Returns names of all attributes in the session. • getId Returns the unique identifier.
  • 12.
    Tracking access count publicclass ShowSession extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); HttpSession session = request.getSession(); String heading; Integer accessCount = (Integer)session.getAttribute("accessCount"); if (accessCount == null) { accessCount = new Integer(0); heading = "Welcome, Newcomer"; } else { heading = "Welcome Back"; accessCount = new Integer(accessCount.intValue() + 1); } session.setAttribute("accessCount", accessCount);
  • 13.
    Tracking access count PrintWriterout = response.getWriter(); out.println (docType +"<HTML>n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>n" + "<BODY BGCOLOR="#FDF5E6">n" + "<CENTER>n" + "<H1>" + heading + "</H1>n" + "<H2>Information on Your Session:</H2>n" + "<TABLE BORDER=1>n" + "<TR BGCOLOR="#FFAD00">n" + " <TH>Info Type<TH>Valuen" + " <TD>Number of Previous Accessesn" + " <TD>" + accessCount + "n" + "</TABLE>n" + "</CENTER></BODY></HTML>");
  • 14.
    Summary • Sessions donot travel across network - Only unique identifier does • Get the session - request.getSession • Extract data from session - session.getAttribute • Do typecast and check for null • If you cast to a generic type, use @SuppressWarnings
  • 15.
    Summary • Put datain session - session.setAttribute • Custom classes in sessions - Should implement Serializable