Writing a simple web application with Spring boot

Spring is an open-source JAVA application framework that lets you write enterprise java applications. Spring boot is basically a quick way for you to startup a spring application. Spring enables you to write very complex applications in a matter of minutes. I will not go deep into Spring and spring boot applications, instead, I will just dive into the application.

Following are the prerequisites for this tutorial.

  • Java 8 installed.
  • Intellij Idea (or you can use Spring tools by https://spring.io/tools).
  • For this tutorial, I will be using Apache Maven installed.

First, let’s go ahead and create a maven project. I will use sample-spring-app as the project name.

Since this is a simple maven project, we need to make this a spring project. So add the following snippet to the pom.xml.

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

Adding this to the pom made our project a child project of the spring-boot-starter-parent project. Adding this will import all the default configurations to our project. Since we are developing a web application, we need to add the required web-related dependencies. Sounds hard right? Don’t worry just add the spring-boot-starter-web dependency. So my pom.xml will look like this.

Let's go ahead and a class that will be the starting point of our application. While creating the class make sure to add a main method.

Adding the main the method will make sure this application can stand-alone. So we have to add the code inside the main method which tells spring that this is a spring application, to create and start a servlet container, and host this application. It sounds like we have to do a lot of coding inside this method right? With spring it’s not that hard.

Having the @SpringBootApplication annotation and invoking the run method will make this a stand-alone application. Yep, that’s it. This is the most simple web application that you can have. Run this main method and notice the following in the terminal window.

So this tells us that your application has started in port 8080 in Tomcat. Navigate to http://localhost:8080/ and you will notice the following screen.

This is a fallback error page from and this does not say that your application did not start. What this page says is that there were no mapping for this URL, so tried to find /error page, but there were none and so you are redirected to this fallback page.

So coming back to my previous point, making this application stand-alone, the following two important things will happen.

  • Performs a path scan
  • Start Tomcat server.

How Spring identifies different components is via annotations and applies configurations according to the annotation type (do not worry about this, you’ll get to know more about these annotations in the following sections). That is why we were able to get a running web application by adding a simple code snippet.

Finally, it deploys the application on a Tomcat server which making this a stand-alone application. Notice that you did not have to download and install Tomcat, instead, it was supplied by Spring. That's how spring makes your life easy.

Our aim is to have a web application and can handle different types of requests. In spring the class that handles the requests is called a controllery. So with the SampleApplication class, I will add a controller.

Adding the @RestController annotation will make this class a controller and @RequestMapping annotation will map the getWelcomeMessage method to http://localhost:8080/hello-world URL. Since this is in the same classpath as the Spring main class, you can just re-run the main method. Visit the above URL and notice the hello world message in the browser window.

When we create web applications, we don’t return strings. We return more complex JSON responses. Let’s see how we can do that. So my requirement now is to have an API to get the user name and userId. First I will add a model class.

Now I will add a new controller to return a list of user details.

In the above code, the getUserList method is mapped to the http://localhost:8080/users GET request. Adding the annotation @RestController will make sure to convert the returned objects to JSON. Re-run the main method and go to the above link.

So now let's see how we can improve this controller to support POST requests. So my new requirement to introduce a new endpoint to add a new user to the system. So to manage users, I want to introduce a user management service. I can do so by adding @Sevice annotation to a class. So adding the annotation will make this a singleton class and mark it as a business service.

Now I’m going to edit my UserMgtController class to use this service.

So here, in line 18, I have marked used @Autowired annotation to bind the UserManagementService with the rest controller. Comparing to the previous implementation, I have modified the getUserList method to use the service and I have introduced addUser method to map the method a POST request made to the /users/add endpoint. Here I have specified that addUser method will consume a User type body in the API request. Now make POST request the above http://localhost:8080/users/add with the following as the request body (Note: make sure to set the add the Content-Type header with application/json as the value).

{
"username" : "monika",
"userId" : "4654-dbdbdgr-3243tgffdv-5463"
}

Notice that you have received 200 OK API response. Now do a GET request to the /users endpoint and notice that the new user has been added to the service.

Now I want to improve this web application to read the username from a path variable and get the corresponding userId. First I will introduce the following method to my service to get the userId from the username.

public String getUerId(String username) {
for (User user : userList) {
if (user.getUsername().equals(username)) {
return user.getUserId();
}
}
return "";
}

Now I will add the following method to the UserMgtController.

@RequestMapping("/users/{Username}")
public String getUserId(@PathVariable("Username") String username){
return userManagementService.getUerId(username);
}

Notice that I have added to a variable in the request mapping section and I have mapped that variable to the method parameter via @PathVariable annotation. (NOTE: If the request path variable name is similar to the parameter name in the method, we do not need to specify the request path variable name in the argument section of the annotation).

Now make a GET request to the /users endpoint with a username in the request URL. A sample request will look like this.

http://localhost:8080/users/Chandler

Notice that you have received the userId of the user that was specified in the original request. So this is how you write a very simple web application and this took just around 5 minutes. This is how Spring makes your life easy.

As for now, we have used Intellij Idea to start and stop the application. Instead, we can create a .war or a .jar file and deploy it separately. First, you need to add the main classpath to the pom.xml.

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>org.sominda.sample.spring.app.SampleApplication</mainClass>
</configuration>
</plugin>
</plugins>
</build>

If you want to deploy the web application as a .jar, do a mvn clean install, navigate to the .jar file location and enter the following command.

java -Xms128m -Xmx256m -jar sample-spring-app-1.0-SNAPSHOT.jar

If you want to deploy as a war, firs change the packaging type to .war by adding the following snippet to the pom.xml.

<packaging>war</packaging>

Finally, navigate to the war file location, and enter the following command.

java -Xms128m -Xmx256m -jar sample-spring-app-1.0-SNAPSHOT.war

So this is how to write a very basic web application. You can find the full source code here.

From the next blog, I will explain how to provide log4j2 support to a spring application. Don’t forget to applause if you have learned something from this blog.

A big eager beaver