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/

  • Levente

    in the Pom.xml in the 49. row is missing a $ sign
    but good work

    • NameNotTaken

      Thanks Levente.

      I’ve corrected the code above. The downloadable POM wasn’t affected.

  • Abhishek

    in the WebInitializer class “servlet.addMapping(“/”); ” is not working.

    infact servlet.addMapping(“*.do”); is working.

    could you please correct me.

    • NameNotTaken

      Thanks for the comment Abhishek.

      (Just for others reading this, servlet.addMapping(“/”) does work. It’s been tested on Glassfish and Tomcat)

      *.do would only work if you’re controller was expecting URL’s ending in .do.

      Are you using Struts1 in your project too by any chance? It uses .do. Or could there be any other Servlets configured which may be conflicting with the Spring dispatcher servlet?

  • sander

    really great tutotrial. thank You!

  • Alonso

    I downloaded and opened your NetBeans project and i got this. It’s seems that CSS not found

    • Mahsa

      in the jsp file a $ sign is missing before {cp} where it sets the css file:

  • An excellent tutorial. You might want to add the content of the .css file to your example. Without it it fails with a resource not found.

    • Hi Trilliji

      Thanks for the comment.

      The comment below from Alonso suggests the same problem. I’m simply not seeing it on Glassfish 4.1 or Tomcat 8.0.9.0.

      Can you view source and click into the css file?
      What is the path to the CSS file when you view source?

      What are you doing to fix the problem? Or what do you think it is? Any information you can provide I’m sure will help others.

      I’m not sure i understand what you mean by “the content of the CSS file”

      Thanks very much, your contribution is appreciated.
      John

      • Oh, just include the .css file inline in your text rather than having to download it. I could get it from the download. It was a wee little nickpick of a suggestion. Would love to see one with spring security added.

  • Jay Mark Domugho

    Hi, this is a very excellent tutorial. I was just wondering if you can have an example for Security. maybe a simple login implementation?

    Thanks

  • Maxim Livshitz

    big thank you very much

  • Claudio Fresta

    Hey, I got an issue right here.

    When I run the project, the project folder automatically removed from netbeans and tomcat undeploy the project by itself, and getting 404 as a result.
    But when I build the project, the project folder still there, said the project successfully build. But I still got the 404 code in browser.

    Where did I go wrong?

    ps: I use tomcat v8.

    Thanks, I really appreciate your help.

  • Claudio Fresta

    Hi, I got a problem here,

    When I run the program, it says “FAIL – Deployed application at context path /Spring4AnnotationConfig but context failed to start”.

    Why is that?
    Thanks for the tutorial, really appreciate your help.

    • Claudio Fresta

      Solved.

      I change the Spring version to the latest (4.2.1) from pom.xml and change jstl group-id from jstl to javax.servlet.

      Thanks! 🙂

      • Hi Claudio

        Thanks very much for sharing the solution. Sorry I wasn’t able to help.

        John

        • Claudio Fresta

          No problem, awesome stuff you have here, keep sharing! 🙂

    • Claudio Fresta

      For anyone with resource files not loaded,

      try to change
      registry.addResourceHandler(“/resources/**”).addResourceLocations(“/WEB-INF/resources/*”);
      to
      registry.addResourceHandler(“/resources/**”).addResourceLocations(“/WEB-INF/resources/”);

      and remove {cp} from url into your static resources.

      Source: http://stackoverflow.com/questions/25061237/spring-4-addresourcehandlers-not-resolving-the-static-resources
      (Vijay answer)

      Might help, thanks again for this awesome tutorial! :))

  • Jan Erik Berglund

    java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: java.lang.ClassNotFoundException: org.springframework.core.OrderComparator$OrderSourceProvider

  • Jan Erik Berglund

    I’m use glassfish 4 java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: java.lang.ClassNotFoundException: org.springframework.core.OrderComparator$OrderSourceProvider

  • Nagendra

    Caused by: java.lang.IllegalArgumentException: Invalid /*.do in servlet mapping

  • Nagendra

    Caused by: java.lang.IllegalArgumentException: Invalid /*.do in servlet mapping

  • frank_new_year

    The resources are not loading also with the solution of Claudio Fresta. This not working with netbeans 8.1

    • David J. Chirinos

      Move the resources folder to the Web Pages folder.

      In Config.java change

      registry.addResourceHandler(“/resources/**”).addResourceLocations(“/WEB-INF/resources/*”);

      to:

      registry.addResourceHandler(“/resources/**”).addResourceLocations(“/resources/*”);

      This worked for me

      • Thanks very much David

  • David J. Chirinos

    Thank you for this awesome tutorial!! 😀

  • Nauman

    thank you so much . this stuff is very helpful.

  • Ethan Wilansky

    Finally, an up-to-date, succinct and well-explained post on using Spring MVC 4 with an annotations controller. It’s this type of resource that will help web developers adopt this framework.

  • Ethan Wilansky

    One small correction: on index.jsp, the reference to site.css should be preceded with $ so instead of this:
    href=”{cp}/resources/css/site.css”
    it should be this:
    href=”{cp}/resources/css/site.css”

  • FaisalHyder

    Hi John, very nice article , please share it with Spring Boot Security log-in and log-out example there are so many tutorials out there but they don’t tell how to exactly use css and js files in Spring Security project, @EnableWebMvc in WebMVCConfigurerAdapter extending class causes issue for loading css content on Pages, kindly provide an article with that. waiting for it 🙂
    Once again thanks…

    • FaisalHyder

      After a week of head scratching , i finally made it to work. 🙂 Resources are getting loaded even with @EnableWebMvc and authenticated requests. 🙂 thanks for your tutorial, if anyone needs help feel free to ask. 🙂