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

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

[...]  
  
<properties>                                                                   
 <project.build.sourceencoding>UTF-8</project.build.sourceencoding>         
  
 <slf4j.version>1.6.1</slf4j.version>                                       
 <logback.version>1.0.6</logback.version>                                   
 <org.springframework.version>3.1.2.RELEASE</org.springframework.version>   
 <javax.jstl.version>1.2</javax.jstl.version>                               
  
</properties>   
  
[...]  
  
       
<dependency>                                                                      
 <groupid>org.springframework</groupid>                                        
 <artifactid>spring-webmvc</artifactid>                                        
 <version>${org.springframework.version}</version>                             
 <exclusions>                                                                  
  <exclusion>                                                               
   <groupid>commons-logging</groupid>                                    
   <artifactid>commons-logging</artifactid>                              
  </exclusion>                                                              
 </exclusions>                                                                 
</dependency>     
  
[...]  
  
                                 
<dependency>                                  
 <groupid>javax.servlet</groupid>          
 <artifactid>jstl</artifactid>             
 <version>${javax.jstl.version}</version>  
</dependency>     
  
[...]  
  
                             
<dependency>                                 
 <groupid>org.slf4j</groupid>             
 <artifactid>slf4j-api</artifactid>       
 <version>${slf4j.version}</version>      
</dependency>                                
<dependency>                                 
 <groupid>org.slf4j</groupid>             
 <artifactid>jcl-over-slf4j</artifactid>  
 <version>${slf4j.version}</version>      
 <scope>runtime</scope>                   
</dependency>                                
<dependency>                                 
 <groupid>org.slf4j</groupid>             
 <artifactid>slf4j-log4j12</artifactid>   
 <version>${slf4j.version}</version>      
 <scope>runtime</scope>                   
</dependency>  

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

[...]  
<servlet>                                                   
    <servlet-name>spring</servlet-name>                     
    <servlet-class>                                         
        org.springframework.web.servlet.DispatcherServlet   
    </servlet-class>                                        
    <load-on-startup>1</load-on-startup>                    
</servlet>                                                  
<servlet-mapping>                                           
    <servlet-name>spring</servlet-name>                     
    <url-pattern>*.html</url-pattern>                       
</servlet-mapping>   
[...]  

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   
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
http://www.springframework.org/schema/context   
http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  
 <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">  
 </property></property></property></bean>  
</context:component-scan></beans>

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>  
<a href="http://www.blogger.com/helloworld.html"> Hello world.</a>  
</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.

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.

Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button