Spring Web Application Example
In this article we will see how to develop a simple web application using Spring framework. This is a very simple example of developing a spring web application; it does not go into the details of performance, security, scaling etc.
1. Introduction
Spring Framework is a Java platform that provides comprehensive infrastructure support for developing Java applications. Spring handles the infrastructure so you can focus on your application. Spring enables to build applications from “plain old Java objects” (POJOs) and to apply enterprise services non-invasively to POJOs.
The Spring Framework consists of features organised into multiple modules. These modules are grouped into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation, and Test.
2. Spring MVC
Spring Web MVC is the original web framework built on the Servlet API and included in the Spring Framework from the very beginning. The formal name “Spring Web MVC” comes from the name of its source module spring-webmvc
but it is more commonly known as “Spring MVC”. Spring MVC, like many other web frameworks, is designed around the front controller pattern where a central Servlet
, the DispatcherServlet
, provides a shared algorithm for request processing while actual work is performed by configurable, delegate components. This model is flexible and supports diverse workflows.
The DispatcherServlet
, as any Servlet
, needs to be declared and mapped according to the Servlet specification using Java configuration or in web.xml
. In turn the DispatcherServlet
uses Spring configuration to discover the delegate components it needs for request mapping, view resolution, exception handling, and more.
DispatcherServlet
expects a WebApplicationContext
, an extension of a plain ApplicationContext
, for its own configuration. WebApplicationContext
has a link to the ServletContext
and Servlet
it is associated with. It is also bound to the ServletContext
such that applications can use static methods on RequestContextUtils
to look up the WebApplicationContext
if they need access to it.
3. Example
For this we will use IDEA IntelliJ (2017.2) to build the application. For this you will need Java 1.8 or later, Maven 3.0+. We will build an application that will have a static page and will also accept HTTP GET request at
http://localhost:8080/hello
and respond with a web page displaying HTML. The body of the HTML contains a greeting:
"Hello Mr, How are you."
You can customise the greeting with an optional ‘user‘ parameter in the query string:
http://localhost:8080/greeting?user=Meraj
The user parameter if passed is included in the response as below:
"Hello Meraj, How are you."
3.1 Maven
First you set up a basic build script. You can use any build system you like when building apps with Spring, but the code you need to work with Maven is included here. In a project directory of your choosing, create the following subdirectory structure; for example, with mkdir -p src/main/java/hello
on *nix systems.
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javacodegeeks</groupId> <artifactId>spring-web-application</artifactId> <version>1.0.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies> <properties> <java.version>1.8</java.version> </properties> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
The Spring Boot Maven plugin provides many convenient features. It collects all the jars on the classpath and builds a single, runnable “über-jar”, which makes it more convenient to execute and transport your service. It searches for the public static void main()
method to flag as a runnable class. It provides a built-in dependency resolver that sets the version number to match Spring Boot dependencies. You can override any version you wish, but it will default to Boot’s chosen set of versions.
3.2 Web Controller
In Spring’s approach to building web sites, HTTP requests are handled by a controller. You can easily identify these requests by the @Controller
annotation. In the following example, the HelloController
handles GET
requests for /hello
by returning the name of a View, in this case, “hello”. A View is responsible for rendering the HTML content:
HelloController.java
package hello; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class HelloController { @RequestMapping("/hello") public String hello(@RequestParam(value="user", required=false, defaultValue="Mr") String user, Model model) { model.addAttribute("user", user); return "hello"; } }
This controller is concise and simple, but there’s plenty going on. Let’s break it down step by step. The @RequestMapping
annotation ensures that HTTP requests to /hello
are mapped to the hello()
method. The above example does not specify GET vs. PUT, POST, and so forth, because @RequestMapping
maps all HTTP operations by default. Use @RequestMapping(method=GET)
to narrow this mapping.
@RequestParam
binds the value of the query String parameter user into the user parameter of the hello()
method. This query String parameter is not required; if it is absent in the request, the defaultValue
of “Mr” is used. The value of the user parameter is added to a Model object, ultimately making it accessible to the view template.
The implementation of the method body relies on a view technology, in this case Thymeleaf, to perform server-side rendering of the HTML. Thymeleaf parses the hello.html
template below and evaluates the th:text
expression to render the value of the ${user}
parameter that was set in the controller.
hello.html
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Hello World</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> </head> <body> <p th:text="'Hello ' + ${user} + ', How are you.'"/> </body> </html>
3.3 Execution
Although it is possible to package this service as a traditional WAR file for deployment to an external application server, the simpler approach demonstrated below creates a standalone application. You package everything in a single, executable JAR file, driven by a good old Java main()
method. Along the way, you use Spring’s support for embedding the Tomcat servlet container as the HTTP runtime, instead of deploying to an external instance.
Application.java
package hello; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
@SpringBootApplication
is a convenience annotation that adds all of the following:
@Configuration
tags the class as a source of bean definitions for the application context.@EnableAutoConfiguration
tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.- Normally you would add
@EnableWebMvc
for a Spring MVC app, but Spring Boot adds it automatically when it seesspring-webmvc
on the classpath. This flags the application as a web application and activates key behaviours such as setting up aDispatcherServlet
. @ComponentScan
tells Spring to look for other components, configurations, and services in the hello package, allowing it to find the controllers.
The main()
method uses Spring Boot’s SpringApplication.run()
method to launch an application. Did you notice that there wasn’t a single line of XML? No web.xml
file either. This web application is 100% pure Java and you didn’t have to deal with configuring any plumbing or infrastructure.
You can run the application from the command line with Maven. Or you can build a single executable JAR file that contains all the necessary dependencies, classes, and resources, and run that. This makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.
You can run the application using ./mvnw spring-boot:run
. Or you can build the JAR file with ./mvnw clean package
. Then you can run the JAR file:
java -jar target/spring-web-application-1.0.0-SNAPSHOT.jar
The app should be up and running within a few seconds.
3.4 Testing
Now that the web site is running, visit http://localhost:8080/hello
, where you see:
"Hello Mr, How are you."
Provide a name query string parameter with http://localhost:8080/hello?user=Meraj
. Notice how the message changes from “Hello Mr, How are you.” to “Hello Meraj, How are you.”
This change demonstrates that the @RequestParam
arrangement in HelloController
is working as expected. The user parameter has been given a default value of “Mr”, but can always be explicitly overridden through the query string.
4. Adding static content
Static resources, like HTML
or JavaScript
or CSS
, can easily be served from your Spring Boot application just be dropping them into the right place in the source code. By default Spring Boot serves static content from resources in the classpath at /static
(or /public
). The index.html
resource is special because it is used as a welcome page if it exists, which means it will be served up as the root resource, i.e. at http://localhost:8080/
in our example. So create this file:
index.html
<!DOCTYPE HTML> <html> <head> <title>Hello World!</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <p>Have a lovely day <a href="/hello">here</a></p> </body> </html>
and when you restart the app you will see the HTML at http://localhost:8080/
.
5. Conclusion
In this article we saw how to build a simple web application using Spring. First we discussed what Spring framework is and what problems it solves then we discussed about the Spring Boot. Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”. In the above example we saw how easy it is to build and run an application and it avoids the pain of deployment to a web/application server as well.
6. Download the Source Code
This was a very simple example of writing a web application using Spring framework.
You can download the full source code of this example here: Spring Web Application Example