Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Saturday, 19 January 2013

Spring 3 MVC hello world example in Eclipse

Spring is the most popular and widely used open source java application framework as of current date.  This blog will help you to create your very first Spring MVC hello world Application in Eclipse. In this part of our Spring tutorials series, we will try to create a simple Spring MVC application which would start with a welcome page displaying a link “Say Hello”. On clicking this link, user will be redirected to another page displaying a message “Hello World, Spring 3.0!”.
Open Java EE perspective in your Eclipse and create a new Dynamic Web Project. Project structure can be shown in fugure :


Now add all required jar files in lib folder of your application. These libraries are taken from spring-framework distribution.

WebContent > WEB-INF > lib

spring-hello-world-libraries

Now add following files one by one according to the application structure:

WebContent\WEB-INF\web.xml
This is the entry point for every web application, it tells the container about request handlers, welcome file and how the application is going to behave. A servlet named DispatcherServlet is registered with url pattern *.html , this configuration make sure that all the requests ending with .html are going to be handled by spring framework itself.
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 id="WebApp_ID" version="2.5">

 <display-name>Spring3MVC</display-name>

 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>

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

</web-app>


WebContent\index.jsp
This is a simple jsp file that provides a link to hello.html , on clicked a url is requested and mapped with an appropriate controller.
<html>
<head>
<title>Java Guys | Home</title>
</head>
<body style="font-family:Segoe Print ">
<center>
<div > <a href="hello.html">Say Hello</a></div>
</center>
</body>
</html>

WebContent\WEB-INF\spring-servlet.xml
This is core of all spring applications , all configuration and implementation is done here. tag <context:component-scan>.is used to scan all content in package javaguys.tutorials.spring so that all controller can be made available to map exact url pattern. There is bean defined with id viewResolver , this is responsible to add suffix and prefix values to view names defined under ModelAndView object.
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
 xmlns:context="http://www.springframework.org/schema/context"
 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="javaguys.tutorials.spring" />
 <bean id="viewResolver"
  class="org.springframework.web.servlet.view.UrlBasedViewResolver">

  <property name="viewClass"
   value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/WEB-INF/jsp/" />
  <property name="suffix" value=".jsp" />

 </bean>
</beans>

src\javaguys\tutorials\spring\HelloWorldController.java
Actual work is done here as a request with /hello is arrived this controller is mapped and helloWorld() method is executed. A object of type ModelAndView is returned which takes two parameters "hello" is view name and a string value mapped to message key.
package javaguys.tutorials.spring;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {

  @RequestMapping("/hello")
     public ModelAndView helloWorld() {

         String message = "Hello World, Spring 3.0!";
         return new ModelAndView("hello", "message", message);
     }
}

WebContent\WEB-INF\jsp\hello.jsp
This is a simple jsp  page that renders a string using expression ${message} the value of message is being set in controller.
<html>
<head>
<title>Java Guys | Home</title>
</head>

<body style="font-family:Segoe Print ">
<center>
<div >  ${message}</a></div>
</center>
</body>

</html>

Now we are all done with our first Spring MVC application , run application on Server to see the Result .

spring-hello-world

spring-hello-world

In upcoming blogs we w'll see other concepts, tutorials, tips and tricks related to Struts2 , Spring and Hibernate Technologies .










Thanks for reading !
Being Java Guys Team

Download "Struts3 MVC HelloWorld Example" from "SkyDrive"





5 comments:

  1. u r really wonderfull.............superb...i am a software engineer..........thanks alot

    ReplyDelete
  2. Great. Spring MVC indeed is my favorite Java Web framework. Clean and feels right (intuitive)

    ReplyDelete
  3. I am facing thi error :
    Aug 31, 2014 3:01:35 PM org.apache.catalina.core.AprLifecycleListener init
    INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre7\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;.
    Aug 31, 2014 3:01:35 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
    WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:SpringHelloWorld' did not find a matching property.
    Aug 31, 2014 3:01:35 PM org.apache.coyote.AbstractProtocol init
    INFO: Initializing ProtocolHandler ["http-bio-8080"]
    Aug 31, 2014 3:01:35 PM org.apache.coyote.AbstractProtocol init
    INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
    Aug 31, 2014 3:01:35 PM org.apache.catalina.startup.Catalina load
    INFO: Initialization processed in 1116 ms
    Aug 31, 2014 3:01:35 PM org.apache.catalina.core.StandardService startInternal
    INFO: Starting service Catalina
    Aug 31, 2014 3:01:35 PM org.apache.catalina.core.StandardEngine startInternal
    INFO: Starting Servlet Engine: Apache Tomcat/7.0.50
    Aug 31, 2014 3:01:37 PM org.apache.catalina.core.ApplicationContext log
    INFO: Initializing Spring FrameworkServlet 'spring'
    Aug 31, 2014 3:01:37 PM org.springframework.web.servlet.FrameworkServlet initServletBean
    INFO: FrameworkServlet 'spring': initialization started
    Aug 31, 2014 3:01:37 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
    INFO: Refreshing WebApplicationContext for namespace 'spring-servlet': startup date [Sun Aug 31 15:01:37 IST 2014]; root of context hierarchy
    Aug 31, 2014 3:01:38 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
    INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/spring-servlet.xml]
    Aug 31, 2014 3:01:38 PM org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider registerDefaultFilters
    INFO: JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
    Aug 31, 2014 3:01:38 PM org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider registerDefaultFilters
    INFO: JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
    Aug 31, 2014 3:01:38 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
    INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@34fd2520: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,viewResolver]; root of factory hierarchy
    Aug 31, 2014 3:01:38 PM org.springframework.web.servlet.FrameworkServlet initServletBean
    INFO: FrameworkServlet 'spring': initialization completed in 718 ms
    Aug 31, 2014 3:01:38 PM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["http-bio-8080"]
    Aug 31, 2014 3:01:38 PM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["ajp-bio-8009"]
    Aug 31, 2014 3:01:38 PM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 2761 ms
    Aug 31, 2014 3:01:50 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
    WARNING: No mapping found for HTTP request with URI [/SpringHelloWorld/hello.html] in DispatcherServlet with name 'spring'
    Aug 31, 2014 3:01:52 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
    WARNING: No mapping found for HTTP request with URI [/SpringHelloWorld/hello.html] in DispatcherServlet with name 'spring'

    ReplyDelete
  4. Check you helloWorldComtroller if you have mentioned request mapping properly

    ReplyDelete

Like Us on Facebook


Like Us On Google+



Contact

Email: neel4soft@gmail.com
Skype: neel4soft