Search This Blog

Spring Framework was created as a result of disappointment of Java community with earlier versions of Enterprise Java. Since then it has grown into huge ecosystem that allows one to solve every problem in building a Web-based Java application and more. Spring is often criticized because it used to rely on XML for configuration purposes. As a response to that the Spring Boot framework was released, which relies on convention over configuration principle and can do without XML at all.

In this tutorial series we’ll go over how to create an application using Spring Framework and Spring Boot. While Spring Boot allows one to create an application faster, Spring is widely used today in enterprise environment and even by startups, so knowing Spring is definitely a marketable skill, and also learning it can provide one with the insight how Spring Boot works. The code for a simple Spring Framework application can be found here and the Spring Boot version here.

Creating Spring Web Application Using Maven Archetype

To create a Spring web application one can rely on maven-archetype-webapp archetype. After that, one should add Spring-related modules to the pom.xml file. One way to go is to use the so-called BOM (Bill of Materials) which allows one not to add version to dependencies. The pom.xml file for our project is shown below.

Now, while we added no code to our application, we can try to build it and deploy. The Maven archetype we used created a index.jsp file located in the webapp/ folder, which we’ll remove later but for now we’ll use to learn how to deploy an application to Tomcat 9 Web-profile application server. To build the application one can use an IDE or execute the following command from CLI.

mvn clean package

Independent of the way you built the application a war file is produced in the target/ sub-folder of the project folder.

Deploying Spring Web Application To Tomcat

The application can be deployed either using an IDE or manually, but before that it is necessary to download Tomcat if it’s not installed on your system and configure it. The installation process is simple: it’s necessary to unzip the downloaded file to some folder and add the path to the bin sub-folder to the PATH variable on your system. In addition, it is necessary to create a CATALINA_HOME environment variable and set it to the path to Tomcat installation folder.

To make possible the access to the Web interface it is necessary to add a single role and a single user to the tomcat-users.xml configuration file situated in the conf/ sub-folder as shown below.

It’s way more faster to deploy the application using an IDE, but here we’ll talk about how to manually deploy the application to Tomcat 9. To start Tomcat server one has to type

catalina.bat start on Windows and

catalina.sh start on Linux.

To check that the server has actually started, navigate to localhost:8080 and the picture shown below should appear.

To stop the server one has to type the same commands with stop instead of start.

The simplest way to manually deploy an application to Tomcat is to copy the generated war file, in our case SpringREST.war, to the webapps/ subfolder of the Tomcat installation folder. After that, just navigate to http://localhost:8080/SpringREST/, where SpringREST is the name of the application, and you should see “Hello World!” greeting in your browser. Another way to deploy an application is to use Manager App from the aforementioned Tomcat Web console.

Adding Configuration Necessary to Run Spring Web Application

Now we’ll remove index.jsp file and create a REST API that returns a greeting instead. First, we need to add a Dispatcher Servlet to web.xml file in the WEB-INF/ subfolder of webapp/ sub-folder. The web.xml file is shown below.

The name of the servlet is dispatcher and Spring will be looking for a file named dispatcher-servlet.xml in the same sub-folder for configuration settings. The file is shown below and instruct Spring to scan classpath in search of the REST controller that serves HTTP requests and returns a greeting.

Now we are ready to create a controller.

Adding Hello World Spring MVC REST Controller

The code for the controller is shown below. The controller is marked with @RestController annotation. Previously we instructed Spring to scan particular packages to look for classes marked with this and some other annotations and use those classes. The annotation tells Spring that this class will serve HTTP requests using Spring MVC.

Also, there is the @GetMapping annotation specifying the path at which the resource can be reached. In our case that means that one can obtain the greeting by localhost:8080/SpringREST/hello URL using HTTP GET method. In earlier Spring version the @RequestMapping annotation was used for specifying paths and HTTP methods used to access a resource.

Testing Spring MVC controllers

A code for a simple test for our controller is shown below. For testing purposes we use the same configuration file but named test-dispatcher-servlet.xml and placed to src/test/resources/ subfolder of our project’s folder.

The test class is decorated with @RunWith annotation that instructs JUnit to run our test with a SpringRunner. The Spring MVC Test framework allows us to test our controller without a servlet container. Inside the test method we make a GET request to our resource and check the response.

Creating a Hello World REST API using Spring Boot

To create a seed Spring Boot project we’ll use Spring Initializr and then open the project using an IDE. We type Web in “Search for dependencies” input field and select “Web” as shown on the picture below and press the “Generate Project” button. The zip file is downloaded after that.

Now, we should add the same REST controller to our Spring Boot project as we created previously. The project can be built using the same command as before, but result is packaged as a jar file by default and uses an embedded Tomcat, so no deployment is necessary, but don’t forget to stop Tomcat before launching the Spring Boot version. The project is launched using the following command.

java -jar target/SpringBootREST-0.0.1-SNAPSHOT.jar

The application is accessible using the URL shown below.

localhost:8080/hello

As to testing the controller, the code of the test method is the same, but annotations on the class change; we do not use XML configuration for this project. The following snippet shows the test class for our controller.

It is seen that it takes less steps to recreate the same application using Spring Boot as a lot of things is inferred by the framework.

Summary

In this post we discussed how to create a simple Hello World REST API using both Spring Framework and Spring Boot. Also, we discussed how to test code using Spring MVC Test Framework. While it’s faster to develop applications using Spring Boot and that’s definitely a benefit for the purposes of learning that it is not necessary to do a lot of configuration, Spring framework is often found in job descriptions and it may be useful to know how a framework works under the hood.

It should be noted, that a Web application can consist of several modules, e.g. it could be a REST API that exposes all the application functionality that can be consumed by an Angular or React front end, a hybrid or native mobile application or a front-end part written in Spring, which consumes the REST API data and republishes it using HTML and some template or component-based Java framework. Creation of Maven multi-module application could be accomplished using pom-root Maven archetype.

Comments

CCTV Installation is belongs to E-sync security solutions.Our primary focus is to be installing cctv cameras and quality and cost effective.There are expected to design your system as per your requirement to the customer feel comfort and secure.We have providing a high quality professional service to the customer.

We'll begin with adding parameters of database connection including credentials, connection URI and database driver name to the application's configuration file. The snippet below shows how to configure the database connection.

MySQL RDBMS was used for our example, but some other DBMS can be used. As we'll use Hibernate to talk to our database, switching databases is a snap, it's only necessary to change t…

Here is a link to my Getting Started with Dropwizard course on Udemy. Only $10! In the previous installment of this series we discussed how to create a Dropwizard project using Maven archetype as well as how to create a simple RESTful API and access it. API security is an important topic and today we'll discuss how to use authentication and HTTPS with Dropwizard. Also, the problem of configuring Dropwizard applications will be touched. All the code for the examples below can be found here.

Authentication

Basic Authentication is a simplest way to secure access to a resource. It boils down to transmitting a base64-encoded column-separated pair of user-ID and password using Authorize HTTP header. If a non-authenticated client tries to access a protected resource, the server prompts the client to provide credentials, that is the aforementioned pair. Otherwise, client may supply the credentials without any prompt from the server. This authentication scheme is a non-secure one as it uses u…

Here is a link to my Getting Started with Dropwizard course on Udemy. Only $10! Dropwizard is a bunch of superb frameworks glued together to provide a fast way of building web applications including REST APIs. We'll talk about great frameworks which are parts of Dropwizard as we go over our examples. The full code for the examples can be obtained here. The simplest way to create a Dropwizard project is to use the Maven archetype called java-simple which is a part of Dropwizard. This can be accomplished either via the command line or using your favorite IDE. Let's stick to the former approach. The command below is formatted for clarity but it should be pasted as a single line to the terminal.

After the project was created it can be modified using an editor or opened in an IDE. All the three IntelliJ, Eclipse and Netbeans have Maven support. An important parameter to note in the pom.xml file of the newly created project is dropwizard.version, which at the time of writing was autom…

Dmitry Noranovich has been programming since 1993 when he learned C language to produce code to carry out computations for his research. Since then he has used C++ and Java for this purpose and as well taught an extracurricular computational physics course in a big university in south Russia. His experience also includes teaching general physics at university level. Besides Java, which is his primary programming language, Dmitry is dabbling in Angular.js and Bootstrap and is passionate about everything concerning REST APIs.
Dmitry is a technology enthusiast and lifelong learner, so he periodically takes MOOCs in computer science and likes to think that someday he will produce one and also tries to learn something new on his own. When he doesn't work, he spends time with his wife and two kids. Should he have spare time, he prefers to spend it hiking or with his Kindle.
Dmitry teaches a Getting Started with Dropwizard course on Udemy (https://www.udemy.com/getting-started-with-dropwizard/?couponCode=blog10).