Enterprise Java

Hello World with Spring 3 MVC

I owe my introduction to Spring to this article by Martin Fowler, way back in 2005. Since then I have tinkered with many a IoC frameworks including Guice, PicoContainer, NanoContainer etc. While I have enjoyed working with IoC in general, I must say Spring has been and continues to be my choice of IoC container for all enterprise grade application development for well over 5 years now.

The latest version of Spring i.e. Spring 3 has been out for a while now. The latest minor version 3.1.1 was released less than a week back, at the time of writing this article. So, as I generally do with latest releases of a few software like Spring, Hibernate, Maven etc I redid – perhaps for the 1000th time – a hello world example with Spring. However, this time I thought I will share this, with the hope that novices in Spring will find the article useful. Keeping in mind the intended audience I felt that an article on Spring MVC will be more useful.

Before I go any further, I must mention that there is no dearth of articles on this subject on net. A few of them are highly recommendable e.g. this one. In my article – unlike the other ones that I have read – I intend to use Eclipse only as an editor and Maven for most of build and dependency management related activities. I am sure others would have written similarly as well. If you know of any good article please let me know and I will mention them here as well.

Without further ado, lets start by creating a vanilla web application using Maven.

File: C:\partha\codeRepo\MavenCommands.bat

REM =============================  
REM Set the env. variables.   
REM =============================  
SET PATH=%PATH%;C:\ProgramFiles\apache-maven-3.0.3\bin;  
SET JAVA_HOME=C:\ProgramFiles\Java\jdk1.7.0  
REM =============================  
REM Create a vanilla web applicaiton.    
REM =============================  
call mvn archetype:create ^  
 -DarchetypeArtifactId=maven-archetype-webapp ^  
 -DarchetypeGroupId=org.apache.maven.archetypes ^  
 -DgroupId=org.academy ^  

This would create a web application springwebapp001. You could deploy that in any servlet container and should be able to hit http://yourmachinename:portnumber/springwebapp001/. It should show you whatever is available at /springwebapp001/src/main/webapp/index.jsp.

Now we will Spring dependencies which will allow us to hijack the http hits to the website. I find this article very informative at this step. It gives you a laundry list of all Spring dependencies. There are a few things worth pointing out though. If you were looking for only Spring MVC, it is not immediately apparent that you could just include dependency for Spring MVC and not the entire list. What is also missed is that you need JSTL as well. Lastly, I think it could have been also mentioned that Spring comes preloaded with commons logging which in my opinion is well and truly on it’s way out – relinquishing it’s seat to Logback or Log4j. So, net net, my version of dependency section in pom looks like this.

File: \springwebapp001\pom.xml


We have got all dependencies in place now and we should be able to do a mvn -e clean install without any hiccups. Once we have done that, now is the time to get Spring into the game. We need to hijack all hits for *.html and hand it to Spring.

File: /src/main/webapp/WEB-INF/web.xml


This means that our application would look for a spring-servlet.xml, where we need to tell Spring what it needs to do with the hits that it intercepts.

File: /src/main/webapp/WEB-INF/spring-servlet.xml

<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans   
 <context:component-scan base-package="org.academy.spring3.controllers">  
 <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="viewResolver">  
  <property name="viewClass" value="org.springframework.web.servlet.view.JstlView">  
  <property name="prefix" value="/WEB-INF/views/">  
  <property name="suffix" value=".jsp">  

Here we have told Spring to look for controllers in org.academy.spring3.controllers package. Lets add one then.

File: /src/main/java/org/academy/spring3/controllers/HelloWorld.java

public class HelloWorld {  
  private final static Logger logger = LoggerFactory.getLogger(HelloWorld.class);   
 public ModelAndView hello(){  
  logger.debug("In the controller.");   
  return new ModelAndView("HelloWorld", "message", "Hello world from Spring3.");   

In this controller we have told Spring to intercept any call to helloworld.html and hand over control to hello(). In this method, we have created a model. The model contains an object called “message” which has a string “Hello world from Spring3.”. This model is handed over to a view called “HelloWorld”. If you look back at spring-servlet.xml you will see “HelloWorld” translates to /src/main/webapp/WEB-INF/views/HelloWorld.jsp. Let’s add some code to that.

File: /src/main/webapp/WEB-INF/views/HelloWorld.jsp

<title>Spring 3.0 MVC</title>  

This code is going to complain a bit on compilation because we have not provided configuration to logback. The following file should do the trick.

File: /src/main/resources/log4j.properties

# Set root logger level to DEBUG and its only appender to A1.  
log4j.rootLogger=DEBUG, A1  
# configure A1 to spit out data in console  
log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%n     

Finally, we just need a convenient way to call the helloworld.html. Let’s modify index.jsp.

File: /src/main/webapp/index.jsp

<h2>Spring 3</h2>  
<a href="http://www.blogger.com/helloworld.html"> Hello world.</a>  

That’s it. Compile and deploy in any servlet container. You have a Spring 3 MVC bare bones example up and running. Give it a go.

Continue to Handling Forms with Spring 3 MVC.

Reference: Hello World with Spring 3 MVC from our JCG partner Partho at the Tech for Enterprise blog.

Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button