Spring 4 Web MVC – Hello World using Annotation and Java configuration with Netbeans

This blog will go through the steps required to setup a basic Spring 4 MVC web application using Netbeans and Maven. The Spring 4 project will be configured using annotations and plain Java rather than XML.

It is a step by step guide to getting up and running quickly. There are plenty alternative methods to doing this but this one is simple, lightweight and to the point. A maven project is available for download at the end of this blog.

Step 1 – Create a new Maven project in Netbeans

Creating an annotation configured Spring 4 web mvc project with maven and netbeans

Choosing maven for Spring 4 Annotation configured project

 

Netbeans has fantastic support for maven. It’s not necessary in this case to issue any maven command lines, Netbeans talks care of all of this for us.

Choose a simsible name and location for the spring 4 web mvc projectChoose sensible options for the project. The above is a rough guide.

Choosing an application server for the annotation configured spring 4 mvc Netbeans maven project

For this example, Tomcat is chosen. Glassfish will also work, choose which ever application server you’re comfortable with.

Hit ‘finish’. The resultant project should now look like this:

Default project created by Maven in netbeans

So far this is just a generic Maven web application project and knows nothing of Spring. When selecting ‘Maven’ as the project type (second image above) Netbeans provides the option to create a project from a maven ‘Archetype’ (Architecture Type). It may have been intuitive to choose an existing ‘Archetype’ for spring at that point. This would result in a fully structured project structured ready to go. However, there are numerous ‘Archetypes’ to choose from so in the interest of keeping things simple, we’ll manually convert this project into a Spring 4 Web MVC project configured by Annotations only, no XML.

Step 2 – Converting the project Structure to Spring 4

Follow these steps then refer to the image below for reference to see that the project structure is correct. File and folder names are important as they are matched in code later.

  1. Delete index.html
  2. Create a WEB-INF folder under the Web Pages folder.
  3. In WEB-INF create a folder called jsp.
  4. In the jsp folder create a jsp called index.jsp.
  5. In WEB-INF create a folder called resources.
  6. In the resources folder create a folder called js and a folder called css.
  7. In the js folder add a file called js.js
  8. In the css folder create a file called site.css

site.css and js.js can have anything in them. The purpose of including them here is to demonstrate how to configure spring to allow them to be included as resources. All requests go through Spring so it needs to know to allow image, script and css url’s through without trying to direct them to some @Controller.

The project should now look like this.

The finished project Spring 4 Java configured Maven project

Still we haven’t gotten to Spring 4 Web MVC (with Java and annotation configuration) yet but we’re about to now.

Step 3  – populating the POM with the artifacts required for Spring 4 Web MVC with annotation / Java configuration.

Update the POM to look like this.

This is pretty much the minimal requirement (but substantial) for Spring. Additional resources can be added as needs be.

Note the version numbesr supplied in the <properties/> section. Note also the five <dependency’s> added. I.e. spring-core, spring-web, spring-webmvc, javax.servlet and jstl.

At this point it’s a good idea to ‘Reload the POM’ in order to download all the required artifacts. The image shows the Java files added in the following steps. Without loading the pom, reference errors occur in the project.

Step 4 – Adding the Java Configurations and Annotations

Create Config.java

(…in package com.outbottle.config)

 

  1. The @Configuration annotation identifies it to Spring as a configuration class.
  2. The @ComponentScan and @EnableWebMVC are somewhat self explanatory and required for Spring to find and configure all annotated classes. Spring will search for annotations on classes specified in the value parameter that is passed to @ComponentScan i.e “com.outbottle”. Therefore if you’ve specified a different root package, adjust accordingly.
  3.  extending WebMvcConfigurerAdapter is necessary in this case to allow ‘resources’ (images, JavaScript, CSS etc.) to be included in the project. To that end the addResourceHandlers() method is overridden. In ‘addResourceHandlers()’ an instruction to Spring is given that when it sees a URL beginning with “resources/**”, let it through and search the actual location “/WEB-INF/resources/*” for the resource (multiple locations can be specified in the addResourceLocations(…) method).

Create WebInitializer.java

(…in package com.outbottle.config)

This is somewhat bog-standard for a web application and simply needs to be there. It mitigates the need for a web.xml in the project.

 

Step 5 – The Web application

 DefaultController.java

  1.  @Controller makes it a controller. i.e. receives requests direct to the corresponding method identified by the @RequestMapping annotation.
  2. In this case there is just one method. The method name is irrelevant. This method is invoked via the url “/” . It returns a view. I.e. the view “index.jsp” as per the matched name “index” = “index.jsp”. The configuration in Config.setupViewResolver() sets prefixes and suffixes around “index” to match it to /WEB-INF/jsp/index.jsp
  3. ModelMap is just one of many  parameters any @Controller method can receive. For more on this see the video on this page: http://spring.io/blog/2010/07/22/spring-mvc-3-showcase/
  4. ModelMap is populated with one key-value-pair for demo purposes before being returned to index.jsp for rendering.
  5. This data is rendered in index.jsp as described next.

index.jsp

  1.  Note that the JSTL library is included in the POM. This is for jsp rendering. The “taglib” is included to allow the context path to be popped into the request (HttpServletRequest) when the page renders.
  2. ${variableName} is used to render values from the request or session. So in this case, {cp} renders the contextPath which is “/Spring4AnnotationConfig”. This allows us to properly reference JS and CSS files.
  3. Note that the path to the JS and CSS files is virtual as configured in Config.java.
  4. ${msg} is used to render the key-value-pair set in the ModelMap in the controller. Similarly, any object or object property can be rendered this way e.g.’ person.name’ where the person class is a bean with a setter and getter for name.
  5. Finally, the <span class=”blue”> is for demo purposes just to show that the virtual path to the resources is working.

The project should now look like this:

 

Reload the POM or run the application to download all required resources and thus remove the reference errors.

Step 6 – Run the application

The running application looks like this:

The finished Spring 4 MVC application with Java configuration

 

Download the code

Spring4AnnotationJavaConfig.zip

Simply unzip. In netbeans Project -> Open and navigate to the unzipped folder. Netbeans will recognize it as a Maven project. Simply open it and hit run.

Conclusion

This blog has outlined the steps involved in building a basic Spring 4 Web MVC Maven project using Netbeans. All spring configuration is done with Java rather than XML.

The project works as is either on Tomcat or Glassfish.

All code involved has been explained.

A Maven project is available for download above.

I hope this is of some help to you in getting to grips with Spring. For more on what Spring can provide take a look at the video on this page: http://spring.io/blog/2010/07/22/spring-mvc-3-showcase/

34 Comments