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 GuicePicoContainerNanoContainer 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

ECHO OFF 

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 ^
 -DartifactId=springwebapp001 

pause

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

[...]

                                                                 
 UTF-8       

 1.6.1                                     
 1.0.6                                 
 3.1.2.RELEASE 
 1.2                             

 

[...]

     
                                                                    
 org.springframework                                      
 spring-webmvc                                      
 ${org.springframework.version}                           
                                                                 
                                                               
   commons-logging                                  
   commons-logging                            
                                                              
                                                                
   

[...]

                               
                                
 javax.servlet        
 jstl           
 ${javax.jstl.version}
   

[...]

                           
                               
 org.slf4j           
 slf4j-api     
 ${slf4j.version}    
                              
                               
 org.slf4j           
 jcl-over-slf4j
 ${slf4j.version}    
 runtime                 
                              
                               
 org.slf4j           
 slf4j-log4j12 
 ${slf4j.version}    
 runtime                 

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

[...]
                                                 
    spring                   
                                           
        org.springframework.web.servlet.DispatcherServlet 
                                          
    1                  
                                                
                                         
    spring                   
    *.html                     
 
[...]
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



 

 
  
  
  
 

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
@Controller
public class HelloWorld {
  private final static Logger logger = LoggerFactory.getLogger(HelloWorld.class); 
 
 @RequestMapping("/helloworld")
 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

<html>
<head>
<title>Spring 3.0 MVC</title>
</head>
<body>
${message}
</body>
</html>
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=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout 
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

<html>
<html>
<body>
<h2>Spring 3</h2>
 Hello world.
</body>
</html> 
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. Happy coding.
Want to read on? May I suggest ...



If you want to get in touch, you can look me up at Linkedin or Google + .

No comments:

Post a Comment