Using Session - novalexei/mod_servlet GitHub Wiki

Using Session

Sometimes we need to store information between the user requests. In other words to maintain the session. But HTTP is stateless protocol and cannot do that. In order to work it around we need to use HTTP Cookies.

mod_servlet supports Cookie based http_session. To illustrate how we can use it let's write a page which will count how many times user visited it. Here is the text of the program:

class tutorial_3_servlet : public http_servlet
{
public:
    void do_get(http_request& req, http_response& resp) override
    {
        resp.set_content_type("text/html");
        http_session &session = req.get_session();
        int& counter = session.ensure_get<int>("counter");
        ++counter;
        std::ostream &out = resp.get_output_stream();
        out << "<!DOCTYPE html>\n"
               "<html>\n"
               "<head>\n"
               "<title>Counter</title>\n"
               "</head>\n"
               "<body>\n"
               "<p>This page was visited by you " << counter << " times</p>\n"
               "</body>\n"
               "</html>\n";
    }
};

SERVLET_EXPORT(tutorial3Servlet, tutorial_3_servlet)

As you can see we acquire the http_session from the request and create (or get, if it already exists) the counter.

Build, deploy, configure and run the servlet and reload the page several times. You'll see the counter growing.

To learn more about cookies see cookie reference page. You can set and read cookies - it is straightforward.

In the next section we will learn how to serve the static content in your web application.

To The Programming Guide

⚠️ **GitHub.com Fallback** ⚠️