17. Sessions

Java application servers (like Tomcat) have built-in support for sessions. They automatically set a cookie for us, and a table that lets us set key/value pairs on the server. We can pull those key/value pairs for each session.

Keep in mind, anything you store in session takes up memory. It also goes away if the server restarts. If you have multiple servers, if the client request goes to a different server, the session information is not there.

In this section we have three examples:

  1. How to set session information.
  2. How to get session information.
  3. How to delete a session.

17.1. session_demo.html

This is a demo HTML file used as a front-end to show sessions at work. It looks like:

../../_images/session_page.png
session_demo.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<!DOCTYPE html>

<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
    <title>Sample Form</title>
</head>

<body>

<!-- Navigation Bar -->
<nav class="navbar navbar-inverse">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                <span class="sr-only">Toggle navigation</span>

                <!-- Three line "hamburger" icon for the collapsed navigation -->
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>

            <!-- Title on nav bar -->
            <a class="navbar-brand" href="#">CIS 320</a>
        </div>

        <div id="navbar" class="collapse navbar-collapse">
            <ul class="nav navbar-nav">
                <li class="active"><a href="index.html">Home</a></li>
                <li><a href="javascript_assignment.html">Javascript Assignment</a></li>
                <li><a href="test_javascript.html">Test Javascript</a></li>
                <li><a href="name_list.html">Name List</a></li>
                <li><a href="form_demo.html">Form Demo</a></li>
                <li><a href="cookie_demo.html">Cookie Demo</a></li>
                <li><a href="session_demo.html">Session Demo</a></li>

            </ul>
        </div>
    </div>
</nav>

<div class="container">
    <h1>Session Demo</h1>
    <h2>Set Session</h2>

    <div>
        <input type="text" id="sessionKey" placeholder="Session Key">
        <input type="text" id="sessionValue" placeholder="Session Value">
    </div>
    <label for="setSessionJava">Back-End Java SetSession</label>
    <button id="setSessionJava">Go</button><br />

    <h2>Clear Session</h2>
    <button id="invalidateSession">Invalidate Session</button>

    <h2>Get Session</h2>
    <label for="getSessionJava">Back-End Java GetSession</label>
    <button id="getSessionJava">Go</button><br />

    <pre id="getSessionResult">
    </pre>

    <br />

</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.3.7/js/tether.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- here is our session demo code -->
<script src="js/session_demo.js"></script>
</body>
</html>

17.2. session_demo.js

This is a JavaScript file that will send info back and forth to our server. There are three scripts, one for setting info, one for getting info, and one for clearing the session. Each one has its own servlet.

session_demo.js
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// This calls our back-end Java program that sets our session info
function setSessionJava() {

    var url = "api/set_session_servlet";

    // Grab data from the HTML form
    var sessionKey = $("#sessionKey").val();
    var sessionValue = $("#sessionValue").val();

    // Create a JSON request based on that data
    var dataToServer = {sessionKey : sessionKey, sessionValue : sessionValue};

    // Post
    $.post(url, dataToServer, function (dataFromServer) {
        // We are done. Write a message to our console
        console.log("Finished calling servlet.");
        console.log(dataFromServer);
        // Clear the form
        $("#sessionKey").val("");
        $("#sessionValue").val("");
    });
}

// This gets session info from our back-end servlet.
function getSessionJava() {

    var url = "api/get_session_servlet";

    $.post(url, null, function (dataFromServer) {
        console.log("Finished calling servlet.");
        console.log(dataFromServer);
        // Update the HTML with our result
        $('#getSessionResult').html(dataFromServer)
    });
}

// This method calls the servlet that invalidates our session
function invalidateSessionButton() {

    var url = "api/invalidate_session_servlet";

    $.post(url, null, function (dataFromServer) {
        console.log("Finished calling servlet.");
        console.log(dataFromServer);
    });
}

// Hook the functions above to our buttons
button = $('#getSessionJava');
button.on("click", getSessionJava);

button = $('#setSessionJava');
button.on("click", setSessionJava);

button = $('#invalidateSession');
button.on("click", invalidateSessionButton);

17.3. SetSessionServlet

This shows how to set a session variable in a JavaServlet. Only takes a couple lines of code.

SetSessionServlet.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package edu.simpson.cis320.crud_app;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "SetSessionServlet", value = "/api/set_session_servlet")
public class SetSessionServlet extends HttpServlet {

    /** Method for posts */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // Set up our response
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();

        // Get the data passed in from the request string
        String sessionKey = request.getParameter("sessionKey");
        String sessionValue = request.getParameter("sessionValue");

        // Get a session object so we can get/set items in our session.
        // This will automatically create a JSESSIONID cookie for us.
        // It also must happen BEFORE we try writing output to the user.
        HttpSession session = request.getSession();

        // Associate, in server memory, a key/value pair.
        session.setAttribute(sessionKey, sessionValue);

        out.println("Done setting the session variable");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

17.4. GetSessionServlet

This is a more complex 3-in-1 example. We see how to set values, how to fetch values, how to get all values.

GetSessionServlet.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package edu.simpson.cis320.crud_app;

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;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

@WebServlet(name = "GetSessionServlet", value = "/api/get_session_servlet")
public class GetSessionServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();

        // --- Sessions ---

        // - This example uses a session to keep count of client requests.
        HttpSession session = request.getSession();

        // At this point, you could grab something out of the session like:
        // String loginId = (String)session.getAttribute("loginId");

        // -- Example  1 --
        // Use a session attribute called "Count" which we'll increase
        // by one each time the user requests it.
        int myCount = 0;

        // Get the count variable
        Integer countObject = (Integer)session.getAttribute("Count");

        // If count is not null, we have a count. Counts have to be stored as
        // objects, and an 'int' isn't an object. So we have to cast it too/from
        // an Integer object.
        if(countObject != null)
            myCount = countObject.intValue();

        // Add one to count, cast it to Integer, store it back into the session.
        Integer newCount = new Integer(myCount + 1);
        session.setAttribute("Count", newCount);

        // -- Example 2 --
        // This example shows how to display the age of a session
        double ageInHours = (System.currentTimeMillis() - session.getCreationTime()) / (1000. * 60. * 60.);
        double lastAccessInHours = (System.currentTimeMillis() - session.getLastAccessedTime()) / (1000. * 60. * 60.);

        out.println(String.format("Session created %.3f hours ago.", ageInHours ));
        out.println(String.format("Last accessed   %.3f hours ago.", lastAccessInHours ));

        // -- Example 3 --
        // This example lists every session variable
        out.println("Session Attributes:");
        Enumeration<String> attributes = session.getAttributeNames();
        while(attributes.hasMoreElements()) {
            String attribute = attributes.nextElement();
            out.println(String.format("  %s = '%s'", attribute, session.getAttribute(attribute).toString()));
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

17.5. InvalidateSessionServlet

InvalidateSessionServlet.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
package edu.simpson.cis320.crud_app;

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;
import java.io.IOException;

@WebServlet(name = "InvalidateSessionServlet", value = "/api/invalidate_session_servlet")
public class InvalidateSessionServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Get the session
        HttpSession session = request.getSession();

        // Invalidate it
        session.invalidate();
    }
}