Java Servlet Set/Get Example (original) (raw)

One of the main challenges for every beginner in the development world is to understand and assimilate how things works internally in a technology in order to create their own code. More than that, make this code working, flexible, standardized and functional for a project that, most of the times, is already running.

Servlets are known for their complexities regarding the way code works inside of the specification core. When it comes to manipulate data and navigate it from one place to another, this complexity can increase considerably (even more if we’re talking about JSPs, Expression Language, scopes, etc.).

Besides all that, we still have to remember that a web application, published on a server, has to deal with multiple threads/requests arriving all the time, a session management for each different user that starts a communication with the same application, a context for the whole system in order to maintain important data the container and the application itself are going to use to exchange information and keep things under control.

This article aims to facilitate part of this understanding. Specifically talking about the Java Servlet Set/Get variables. Variables help us to store data in different types of scopes and get it further in our pages, other servlets, in everywhere we have a request object in hands. Now, we’re going to see, in practice, some examples of how to best use them.

1. Servlet Scopes

There are three main servlet scopes in Java web: request, session and application (or context) scopes. Let’s see what is the difference among them:

Let’s create a new web application of our Set/Get Attribute Example in Java, using the latest version of Eclipse IDE and Tomcat. Despite of being possible to create a whole web application with Maven, we’re going to simplify using the native IDE internal tools.

So, create a new project going to File > New > Dynamic Web Project. Give the project a name and select the proper target runtime configurations:

Java Servlet Set/Get - Dynamic Web Project

Creating new Dynamic Web Project

At this time, you must have already downloaded and set up Tomcat to your IDE (see the default configuration for Apache Tomcat). Click Next until the end and leave all the options with their respective default values.

Once you finish the project setup, let’s gonna create our Servlet class in order to better understand how to set and get variables in different scopes.

Go to your project and right click it, then select New > Servlet. In the next screen, inform a package and class name for our servlet:

Java Servlet Set/Get - servlet package/class

Creating servlet package/class

Click Next. In the next screen, you’ll be prompted to inform the description of your servlet (optional, for documentation purposes only), the initialization parameters (if you’re interested on setting up any parameter to your servlet when the container starts up) and the url pattern mappings.

The last one, specifically, is responsible for setting the routes (i.e., the servlet classes) each request that comes to your application is going to be redirected as soon as it arrives. In our case, in order to make the final URI simpler, let’s use the pattern /getset.

Java Servlet Set/Get - servlet url pattern

Setting up the servlet url pattern

Click Next. After that, you’ll see a screen asking for the class modifiers and interfaces your servlet should implement, so just leave them as they come. Regarding the methods stubs, uncheck the doPost, doGet and check the service option. Click Finish.

Java Servlet Set/Get - servlet method options

Selecting servlet method options

2.1. Setting the attributes

Eclipse is going to create some auto generated code, including a constructor and the service method, just like we’ve selected before.

For more details about how a Servlet works, its lifecycle and a hello world example, check our Java Servlet Hello World article.

Next, update your servlet class with following code:

GetSetExampleServlet

package com.javacodegeeks.servlet.example;

import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

/**

}

Let’s notice some important things:

2.2. Getting the attributes

Before we can get any of the attributes we’ve just set, we need first to create a JSP (remember, every JSP is, in the end, a Servlet mixed with HTML and controled by the Java web container).

So, go to your /WebContent folder, right click it and select New > JSP File. Give it a name and click Next.

Java Servlet Set/Get - new JSP file

Creating a new JSP file

In the next screen, you’ll be asked to choose a JSP template. Select the New JSP File (html) option and click Finish.

Java Servlet Set/Get - JSP template

Choosing a JSP template

This is going to generate the same JSP code as you see in the template view. Update the file with the following code:

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>

Get/Set Example Message from request: <%= request.getAttribute("mySecretMessage") %>
Message from session: <%= session.getAttribute("mySecretMessage") %>
Message from context: <%= request.getServletContext().getAttribute("mySecretMessage") %>
Message from EL: ${mySecretMessage}
<a href="home.jsp">Go Home!</a>

Let’s understand closer what’s happening here:

Note also that we inserted a link in the end of the page in order to redirect it to another JSP. This is because you need to see what happens with the same variable for each scope when we create a new request.

The code of the new JSP file (home.jsp) can be seen in the following code listing (it is practically the same as the first JSP):

home.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>

Get/Set Example Message from request: <%= request.getAttribute("mySecretMessage") %>
Message from session: <%= session.getAttribute("mySecretMessage") %>
Message from context: <%= request.getServletContext().getAttribute("mySecretMessage") %>
Message from EL: ${mySecretMessage}

3. Running the project

Now, to see our code running, import the project into your Tomcat and start it up. Then, access the following URL at your browser to see the result:

http://localhost:8080/servlet-getset-attrs/getset

If everything is fine you should get the following screen:

Java Servlet Set/Get - Testing the get/set

Testing the get/set example

Observe that each value is properly recovered from the specific context. The EL access it first in the request scope, by default. Let’s then click on the link in the end of the page, you’ll see the following screen:

Java Servlet Set/Get - Home JSP page

Home JSP page

See that, now, the previous value of our request attribute does not exist anymore since we’ve redirected to a new page (and this has generated a new request object). Since we don’t have a request scope anymore, the next one EL is going to access is the session (and, finally, the context in the precedence).

4. Download the Complete Source Code

That was the Java Servlet Set/Get Example.

Download
You can download the full source code of this example here: servlet-getset-attrs

Photo of Diogo Souza

Diogo Souza works as Java Developer at PagSeguro/UOL and has worked for companies such as Fulcrum Worldwide, Indra Company, Atlantic Institute and Ebix LA. He is also an Android trainer, blogger, speaker at events on Java and mobile world and a DevMedia consultant. Today, most of his time is used to study about new techonologies as well as write about them, specially the ones based on back-end, big data, performance and scalability of large systems.