Learn Servlet-JSP By Building A Social Network Website — Part VII

Sera Ng.
Tech Training Space
7 min readOct 28, 2020

Learn session technique and how to apply to the login feature

Task 10: Reading — Session

For the next tasks, we will be using sessions very often. That is the reason we need to discuss one of the most popular techniques in web development which is called Session.

HTTP is the main protocol that is used for communicating web-related data between a web browser and a web server.

One of the common characteristics of HTTP is that it is a stateless protocol, which means it does not store any data once the response has been transferred to the client (such as a web browser).

However, during the web application life cycle, there are many cases that we need to store user’s data for a period of time. For instance, when a user logged in, the authenticated information needs to be stored so that we don’t ask users to log in again for every action unless they have signed out.

And the session is used for such purposes.

Sessions are used for maintaining user information (also called user state). We can store any kind of data in a session such as a string, an integer, an object, and so on.

A session by itself is stored on the webserver. Each session has a unique identity, called session id, that is allocated for each client.

One way of storing and tracking user information in combination with the session is to use Cookie. Cookie stores pieces of user data for transferring forward and backward between a web browser and a web server.

The main difference between cookie and session is that the cookie is stored on the client-side, and the session resides on the server-side.

Here is a visual way to see how a session works:

Session Model

1: when the browser first sends a request to the web application, the web server creates a new session object with a unique id, for instance, 1234.

2: then, the session is ready to store any data (or state)

3: when the response is sent back to the web browser, the session id (1234) is stored in the response’ header

4: the web browser receives the response and stores the session id in a cookie

From the second request onwards, the web browser sends the request along with the session id so that the web server knows that the client has already had a session and that the session object is fetched for use for that client.

A session lives in the server until one of the following events happens:

  • Users explicitly send a request to invalidate a session. For instance, when a user signs out
  • The session is expired. In the Java web environment, one way to set session time out is in the web.xml:

The configuration indicates that the session will be expired in 30 minutes in case of inactivity.

  • The web app or web server is stopped

You can read more about sessions and cookies at https://docs.oracle.com/cd/E19857-01/819-6518/abxda/index.html

Task 11: Implement Login page

In this task, we are going to implement the login feature with the application of the session as discussed previously.

Step 1:

We need to move the two files news-feed.jsp and profile.jsp into the WEB-INF folder because these two files require users to sign in in order to view.

Files located in WEB-INF folder cannot be accessed directly from the web browser. They can only be forwarded or directed from a servlet or JSP.

Step 2:

We are going to need a new key for another attribute. So, let’s add the following key to the Keys class:

public static final String USER = “user”;

That key will be used for storing user objects in the session’s attribute when a user signs in successfully.

Step 3:

As mentioned in the database setup section, we store the user’s avatar in binary format (blob data type) in the database. Therefore, in order to display the user’s avatar in the web browser, one of the convenient ways is to convert the binary data image into a base64 string.

If you have not heard about base64, take some minutes to read at https://en.wikipedia.org/wiki/Base64

And how to show base64 image using image tag: https://en.wikipedia.org/wiki/Data_URI_scheme

in our application, we need a method to convert blob data type into base64 string.

Let’s create a new class called StringHelper.java in the package net.learnbyproject.helper, and implement the following method:

To convert bytes to base64 string, we just need to call DatatypeConverter.printBase64Binary() method for the task.

But since when a user registers a new account, we do not ask them to supply an image for the avatar, the avatar column in the database for that user will have a null value. Therefore, we need to return a default image to display in the browser.

The above base64 string is the representation of the following image:

Default avatar

Step 4:

In order to check for user account information and perform related tasks, we need to implement the following methods in the UserService class:

We have implemented the extractUser() to extract user details from the ResultSet object since we are going to reuse this method quite often.

There are 3 overloading versions of the getUser() method:

  • getUser(String emailOrPhone, String password): used to get user information based on emailOrPhone and password, which is used as account validation as well
  • getUser(String emailOrPhone): also used to get user information but only based on the emailOrPhone
  • getUser(int id): also used to get a user information but only based on the id

The method checkLogin() just return the getUser() result. We have defined this method just for having better semantic when invoking the method.

Step 5:

Create a new servlet for handling account verification called LoginController in the package net.learnbyproject.controller with the processRequest() method implementation as follows:

To create a session for the user, we invoke the getSession() method in the HttpServletRequest class. This method creates and returns a HttpSession object if there is none, otherwise it returns the current session object.

Then, we check user account information by calling the UserService.checkLogin() method.

If the result returned by UserService.checkLogin() method is not null, which means the user has provided correct login details, we add the current user in the session to indicate that the user has successfully signed in so that we won’t ask the user to sign in again where the authentication is required:

session.setAttribute(Keys.USER, user);

After that, we redirect the user to the page at the URL pattern “newsfeed”:

response.sendRedirect(“newsfeed”);

This URL pattern will be mapped with another servlet we are going to create very soon.

If the account is incorrect, we set the error message and redirect back to the login page

session.setAttribute(Keys.ERROR, “Invalid login information”);
response.sendRedirect(“login.jsp”);

Step 6

In the package net.learnbyproject.controller, let’s create another new servlet to handle the news feed page called: NewsFeedController with URL pattern “newsfeed

Since the news feed page requires users to be authenticated to access, we need to check if the user has signed in or not.

If the sess.getAttribute(Keys.USER) method is not null, that means the user has already logged in, we forward the user to the news-feed.jsp page

Otherwise, we redirect the user to the login.jsp page

Step 7

Open the login.jsp, locate the <form> tag with the id=”body-login-form” and update as the following:

Once a user logged in, we need to provide a way to log out of our system.

Let’s proceed to the next step to implement the logout feature.

Step 8

In the package net.learnbyproject.controller, create a new servlet called LogoutController with the following implementation:

Signing out means that we need to remove the information in the current user’s session. We can do that by calling:

session.invalidate();

But before invoking that method, make sure to check if the user has logged in by performing a check:

session.getAttribute(Keys.USER) != null

Next, open the top_nav.jsp file and add the following snippet as a child of the <ul> tag:

The tag <% … %> in JSP is called scriptlet which we use to execute normal Java code. In our case here, we need to get the session attribute value with the key Keys.USER to check whether a user has logged in. if the user has, the logout link is displayed.

Note that in JSP, we do not need to invoke the HttpSession.getSession() method as we do in servlets. All we need to have a session is to directly make use of the session object.

That’s because as mentioned earlier, JSP fundamentally is a servlet formatted in form of an HTML template. Therefore, instances, such as request, response, and session, that we can use in servlets are also available in JSP pages without any declaration. These objects in JSP are called implicit objects.

Here are some common implicit objects and their corresponding classes

Now everything is ready for tests.

Remember to clean and build your project first.

In the web browser, if you try to access:

http://localhost:8080/cbooksocial/newsfeed

you will be immediately redirected to the login page.

Then, if you input the correct account information, you will be taking to the newsfeed page, and there is the logout link on the right in the top navigation.

One final note about this task:

The purpose of this task is to demonstrate how to use sessions to track user details. The way we did this task is not secure enough to deploy in a production environment.

In real-life applications, it is highly recommended to apply more powerful security frameworks such as Apache Shiro (https://shiro.apache.org/)

If you get stuck, check out the complete source code:

https://github.com/stackera/learn-servlet-jsp/blob/main/Task11_Impl_Login.zip

--

--