Wednesday , June 28 2017
Home / Spring / Spring MVC HelloWorld

Spring MVC HelloWorld

MVC stands for Model View Controller. The Spring MVC framework is one of the popular frameworks across all the frameworks available in the market. Because the advantages of Spring MVC framework tells the importance of Spring MVC.

In this tutorial we are going develop the step by step Spring MVC Helloworld Example using Netbeans.

Spring MVC Helloworld Example:

Step 1: Create a new Project in Netbeans by selecting the new project in File menu and select the web application in the choose project pop-up and click next.

Spring MVC I

Step 2: Give the project name as you want, For now I am giving SampleSpringApplication. Choose the project location where you want to save the project. By default it is in Netbeans projects in your home directory.

Spring MVC II

If you want to place all dependencies (libraries) in one folder, you can check the Use Dedicated Folder for Sorting Libraries option. Then click next.

Step 3 : Select the application server and J2EE version from the drop-down menu. And select next.

Spring MVC III

Step 4: Select the Spring Web MVC frame work from Frameworks menu. You can also select the version of the selected framework in libraries tab. If you want to include the JSTL in your application, you can select the JSTL check box. And click finish.

Spring MVC IV

Step 5 : Yes, we are done. By clicking on the finish button, netbeans will provide us the basic spring application architecture like below.

Spring MVC V

Step 6: Update the diapatcher-servlet.xml like below.


<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
    <context:annotation-config />
    <context:component-scan base-package="controllers" />
    <mvc:annotation-driven />

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />
</beans>

Step 7: Web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Step 8: Create controllers package in Source Package. And Create HelloWorldController.java in controllers package.

HelloworldController.java


import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/helloworld.htm")
public class HelloWorldController {

    @RequestMapping(method = RequestMethod.GET)
    public String helloWorld(ModelMap modelMap) {
        System.out.println("on method");
        modelMap.put("printme", "Hello Spring !!");
        return "index";
    }
}

Step 9: Modify index.jsp like below,


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Welcome to Spring Web MVC project</title>
    </head>
    <body>
        <div style="background-color: green;height: 200px;width: 500px">
            <h1 style="color:black;"> ${printme}</h1>
        </div>
    </body>
</html>

Step 10 : Modify the redirect.jsp like below,


<%@page contentType="text/html" pageEncoding="UTF-8"%>

<% response.sendRedirect("helloworld.htm"); %>

Well, it DONE !!

To run the application

Out put:

Spring MVC Helloworld

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Check Also

Spring Bean Autowire ByType Example

In this tutorial, we are going to learn about one of the autowire strategy in …

5 comments

  1. emre_arikan@yahoo.de'
    Huseyin Emre Arikan

    Thanks for the note. Two humble remarks for improvement:
    1.A tree view after creating the new files would be helpful, so that everyone knows where exactly in the file directory the new files are to be created.
    2.Not the end state of the default files but what is specifically edited (before and after)? That would I have wanted to know.
    Have a great day!

  2. naskavinda@gmail.com'

    Thanks for you lot. This is really help to me start learn Spring framework.

  3. rushimandage91@gmail.com'

    Nice article. Very helpful. I am having some doubts regarding the request flow.
    As per my understanding, request flow is as follows (Please correct me if any thing is wrong) :
    1. Request url is containing ‘helloworld.htm’.
    2. Web.xml tell that any request that contain ‘*.htm’ should be sent to servlet named ‘dispatcher-servlet’
    3. Dispatcher servlet has ‘context : component scan’ . using this, spring understands that there must be some controller class for which there is @Controller annotation for it and @Request Mapping annotation is added with value = ‘helloword.htm’. i.e. all requests with such url pattern should be re-directed to this controller.
    4. Request will check for default method with annotation ‘@RequestMapping(method = RequestMethod.GET)’
    5. Response of this method will be returned.

    My doubts:
    1. How it is determined that response of method ‘helloWorld’ will be returned to index.jsp
    2. What if I want to redirect the response from this method to some other jsp file ?
    3. If I am having multiple methods in controller class, and want to call different methods in different situations, how would I manage it ?
    4. Does the sequence of ‘xmlns:context’ and ‘xmlns:mvc’ matters ?

    Thanks In Advance !

  4. henrikchiang@hotmail.com'

    Hi I’m getting a Error 404
    No mapping found for HTTP request with URI [/SampleSpringApplication/helloworld.htm] in DispatcherServlet with name ‘dispatcher’

    Did I Do something wrong?

  5. vikum.mail@gmail.com'
    Vikum Samaranayake

    Thanks. 😀 Helps a lot. Keep it up

Leave a Reply

Your email address will not be published. Required fields are marked *