Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
SPRING COOKBOOK

You're reading from   SPRING COOKBOOK Over 100 hands-on recipes to build Spring web applications easily and efficiently

Arrow left icon
Product type Paperback
Published in May 2015
Publisher Packt
ISBN-13 9781783985807
Length 234 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Murat Yilmaz Murat Yilmaz
Author Profile Icon Murat Yilmaz
Murat Yilmaz
Jerome Jaglale Jerome Jaglale
Author Profile Icon Jerome Jaglale
Jerome Jaglale
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Creating a Spring Application FREE CHAPTER 2. Defining Beans and Using Dependency Injection 3. Using Controllers and Views 4. Querying a Database 5. Using Forms 6. Managing Security 7. Unit Testing 8. Running Batch Jobs 9. Handling Mobiles and Tablets 10. Connecting to Facebook and Twitter 11. Using the Java RMI, HTTP Invoker, Hessian, and REST 12. Using Aspect-oriented Programming Index

Creating a Spring web application

In this recipe, we will build a simple Spring web application with Eclipse. We will:

  • Create a new Maven project
  • Add Spring to it
  • Add two Java classes to configure Spring
  • Create a "Hello World" web page

In the next recipe, we will compile and run this web application.

How to do it…

In this section, we will create a Spring web application in Eclipse.

Creating a new Maven project in Eclipse

  1. In Eclipse, in the File menu, select New | Project….
  2. Under Maven, select Maven Project and click on Next >.
  3. Select the Create a simple project (skip archetype selection) checkbox and click on Next >.
  4. For the Group Id field, enter com.springcookbook. For the Artifact Id field, enter springwebapp. For Packaging, select war and click on Finish.

Adding Spring to the project using Maven

Open Maven's pom.xml configuration file at the root of the project. Select the pom.xml tab to edit the XML source code directly. Under the project XML node, define the versions for Java and Spring. Also add the Servlet API, Spring Core, and Spring MVC dependencies:

<properties>
  <java.version>1.8</java.version>
  <spring.version>4.1.5.RELEASE</spring.version>
</properties>

<dependencies>
  <!-- Servlet API -->
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
  </dependency>

  <!-- Spring Core -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring.version}</version>
  </dependency>

  <!-- Spring MVC -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
  </dependency>
</dependencies>

Creating the configuration classes for Spring

  1. Create the Java packages com.springcookbook.config and com.springcookbook.controller; in the left-hand side pane Package Explorer, right-click on the project folder and select New | Package….
  2. In the com.springcookbook.config package, create the AppConfig class. In the Source menu, select Organize Imports to add the needed import declarations:
    package com.springcookbook.config;
    @Configuration
    @EnableWebMvc
    @ComponentScan (basePackages = {"com.springcookbook.controller"})
    public class AppConfig {  
    }
  3. Still in the com.springcookbook.config package, create the ServletInitializer class. Add the needed import declarations similarly:
    package com.springcookbook.config;
    
    public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
        @Override
        protected Class<?>[] getRootConfigClasses() {
            return new Class<?>[0];
        }
        
        @Override
        protected Class<?>[] getServletConfigClasses() {
            return new Class<?>[]{AppConfig.class};
        }
    
        @Override
        protected String[] getServletMappings() {
            return new String[]{"/"};
        }
    }

Creating a "Hello World" web page

In the com.springcookbook.controller package, create the HelloController class and its hi() method:

@Controller
public class HelloController {
  @RequestMapping("hi")
  @ResponseBody
  public String hi() {
      return "Hello, world.";
  }
}

How it works…

This section will give more you details of what happened at every step.

Creating a new Maven project in Eclipse

The generated Maven project is a pom.xml configuration file along with a hierarchy of empty directories:

pom.xml
src
 |- main
    |- java
    |- resources
    |- webapp
 |- test
    |- java
    |- resources

Adding Spring to the project using Maven

The declared Maven libraries and their dependencies are automatically downloaded in the background by Eclipse. They are listed under Maven Dependencies in the left-hand side pane Package Explorer.

Tomcat provides the Servlet API dependency, but we still declared it because our code needs it to compile. Maven will not include it in the generated .war file because of the <scope>provided</scope> declaration.

Creating the configuration classes for Spring

AppConfig is a Spring configuration class. It is a standard Java class annotated with:

  • @Configuration: This declares it as a Spring configuration class
  • @EnableWebMvc: This enables Spring's ability to receive and process web requests
  • @ComponentScan(basePackages = {"com.springcookbook.controller"}): This scans the com.springcookbook.controller package for Spring components

ServletInitializer is a configuration class for Spring's servlet; it replaces the standard web.xml file. It will be detected automatically by SpringServletContainerInitializer, which is automatically called by any Servlet 3. ServletInitializer extends the AbstractAnnotationConfigDispatcherServletInitializer abstract class and implements the required methods:

  • getServletMappings(): This declares the servlet root URI.
  • getServletConfigClasses(): This declares the Spring configuration classes. Here, we declared the AppConfig class that was previously defined.

Creating a "Hello World" web page

We created a controller class in the com.springcookbook.controller package, which we declared in AppConfig. When navigating to http://localhost:8080/hi, the hi()method will be called and Hello, world. will be displayed in the browser. This will be explained further in Chapter 3, Using Controllers and Views.

You have been reading a chapter from
SPRING COOKBOOK
Published in: May 2015
Publisher: Packt
ISBN-13: 9781783985807
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image