This is the first article on my blog related to Spring MVC. The beginning is always exciting, so I will try to be concise and informative. Spring MVC allows creation of web-applications in the most convenient, straightforward and fast way. Start working with this technology implies knowledge of Spring CORE. In the post you will read about creation of a simple Spring MVC Controller. I prefer Java-based configuration of application, so the example will contain this approach.

The main aim is a creation of the controller which will process the request. Hence, after a click on the link you will be redirected to a concrete page with the help of Spring controller.

Create in Eclipse a new Dynamic Web Project, then convert it to the Maven project. Verify that your web.xml file looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" 
id="WebApp_ID" version="3.0">

index.jsp will play the role of Home Page in the application, place it into <em>src/main/webapp/index.jsp</em>; Here is the code of index.jsp:

<pre class="html" name="code">
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<h1>Home page</h1>
<p>This is a Home Page.</p>

As the result, project’s structure will be like this:


Setting up dependencies
What I need to do next is to add some dependencies into pom.xml file. I’m not going to speak about dependencies anymore, I will comment the code below:


		<!-- Spring -->
		<!-- CGLIB is required to process @Configuration classes -->
		<!-- Servlet API, JSTL -->

More information about the Spring dependencies you can find on the official blog.

Java-based configuration
It’s time to create a configuration for the application. As I mentioned above this approach is convenient, and one of the reasons is the annotation usage. Firstly I’m going to create WebAppConfig class

package com.sprmvc.init;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

@Configuration //Specifies the class as configuration
@ComponentScan("com.sprmvc") //Specifies which package to scan
@EnableWebMvc //Enables to use Spring's annotations in the code
public class WebAppConfig {
	public UrlBasedViewResolver setupViewResolver() {
		UrlBasedViewResolver resolver = new UrlBasedViewResolver();
		return resolver;


It’s done to point out the path where all JSPs are stored. This is required in order to use further readable URLs.

Now is the turn of Initializer class to be overviewed:

package com.sprmvc.init;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.servlet.DispatcherServlet;

public class Initializer implements WebApplicationInitializer {
	public void onStartup(ServletContext servletContext) throws ServletException {
		AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
		Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));


Notice that Initializer class implements WebApplicationInitializer interface. This is required to avoid XML-configuration of web-application.

JSP for the Controller
Before I show you how to create a simple controller, I need to create a JSP file to which controller will lead us.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

    <p>Hello world: ${message}</p>
    <p>Well done!</p>

Here is the path to the JSP-file: src/main/webapp/WEB-INF/pages/hello.jsp
Notice that in the WebAppConfig class I have specified such path parts like sufix and prefix.

And finally the code of the LinkController class

package com.sprmvc.controller;

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

public class LinkController {

	public ModelAndView goToHelloPage() {
		ModelAndView view = new ModelAndView();
		view.setViewName("hello"); //name of the jsp-file in the "page" folder
		String str = "MVC Spring is here!";
		view.addObject("message", str); //adding of str object as "message" parameter
		return view;

Now you need to update index.jsp file by adding there the link to the Hello Page:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<h1>Home page</h1>
<p>This is a Home Page.</p>
<p><a href="hello-page.html">Hello world link</a></p>

The final project structure is:


Launch the project, open index.jsp and click on the link and you will get:



At times tutorials are really helpful but the best way to learn how to use Spring is to read official documentation, so I recommend you dig deeper on the Spring blog.

About The Author

Mathematician, programmer, wrestler, last action hero... Java / Scala architect, trainer, entrepreneur, author of this blog

  • by the way, what is the advantage of using java based configuration than xml based?
    i find it is easier to load java based configuration application context in spring test via @ContextConfiguration than using xml based, or maybe it’s just me, until now i can’t load xml based config via @ContextConfiguration lol

    • Fruzenshtein

      As for me it’s easy to develop Java-based configuration, it’s more convenient to write in java manner than in xml, it’s easier to navigate through a java code. Annotation-based configuration is more readable

  • Richard

    Hey I am having issue running your example. I get it all setup and it does run but when I attempt to go to the hello.jsp I just get 404’ed. It seems to be some kind of mapping issue like something with spring isn’t working quite right? If you have any suggestions please let me know

    • Fruzenshtein

      Try to clear Tomcat work directory.
      Make a double check of your code and ensure that you do everything as I specified in the tutorial

    • Roman

      I’ve faced the same issue. Can’t figure out what am I doing wrong. Have you solved it? If you have, please let me know. Thanks in advance.

  • airmaxs27781

    Your place is valueble personally. Thanks! …

  • Karthik

    Im getting exception while running this code… donno wot i have missed…

    SEVERE: Error during ServletContainerInitializer processing
    javax.servlet.ServletException: Failed to instantiate WebApplicationInitializer class
    at org.springframework.web.SpringServletContainerInitializer.onStartup(
    at org.apache.catalina.core.StandardContext.startInternal(
    at org.apache.catalina.util.LifecycleBase.start(
    at org.apache.catalina.core.ContainerBase$
    at org.apache.catalina.core.ContainerBase$
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$ Source)
    at Source)
    Caused by: java.lang.NoClassDefFoundError: org/springframework/core/env/EnvironmentCapable
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)

  • eb

    what is the url for running app?

    • Fruzenshtein

      You can see it on the screenshot in the end of the article

  • Fernando Quiroz

    Hi alex,

    Fist open de index.jsp page but when I click the link Hello world link , spring doesn’t recognize the hello.jsp page.

    This is the error.

    Estado HTTP 404 – /SimpleController/hello-page.html

    type Informe de estado

    mensaje /SimpleController/hello-page.html

    descripción El recurso requerido
    (/SimpleController/hello-page.html) no está disponible.

    Apache Tomcat/7.0.12

    • Fernando, the problem you have described can have many reasons.
      Try to clear Tomcat work directory and redeploy the application again.

      If this won’t help you, try to compare your project with mine which I described in the tutorial. Very frequently we forgot some little detail and it triggers big problems

  • dan

    Hi Alex,

    I have the same error like Fernando, and I look very closelly to your tutorial.

  • my2 koseli

    Do you have idea on how to debug this project in eclipse?


  • my2 koseli


    Thank you for your response.

    I had some more questions regarding integrating CXF to spring MVC.

    1) Does it make sense to add Apache CXF to the MVC app to expose WebServices? (I want to expose a REST api through this)

    2) If so, can you give me the annotations that would need to be entered in “WebAppConfig”

    3) Have you integrated MVC in a OSGI container like Karaf? Does it make sense to do so?

  • tryingtocreaethis


    i kept on getting a 404 error when doing this. i tried putting logs in LinkController as well as in WebApplicationInitializer but it appears that their methods were not even called. is there an issue with URLBasedViewResolver that you know of? is manifest required for this to work? thanks!

  • tryingtocreaethis

    me again. is the code for this available over github?

  • sireesha

    hai,i am not able to create jsp pages in main/webapp. what i am doing in main/webapp right click and then new jsp page but it can’t create can u help me? asap

    • I don’t know what IDE do you use. Try to google it. It’s task for children

    • Lisa

      Hi I am having the same issue. Did you manage to resolve it please? I am using Java EE

    • Lu Gao

      just try to update project

  • Lisa

    Hi, I’ve followed all the step and maven tests the project correctly but when I launch it over Tomcat 7.x I get an error 404 not found. Do you know what may be causing this please?

    • Lu Gao

      just check the “deploy assembly”, good luck!

  • Khairul Padzli

    Try change to this instead

  • Naga Rajesh L

    Folks, the dispatcher added on WebAppConfig class needs a seperate namespace. I dont know why it doesn’t accepts a default one say “/*”. Try change dispatcher.addMapping(“/”) to dispatcher.addMapping(“/app/*”)
    It starts recognizing the Views.

  • dee

    Hi, I got an error message:
    The method addServlet(String, DispatcherServlet) is undefined for the type ServletContext

  • hiren

    I tried example code but without maven. Index page gets loaded but when I click on link… i get error

    HTTP Status 404 – /webtest/hello-page
    my jsp folder is under application root folder instead of WEB-INF/jsp. I have added lib folder to WEB-INF and copied spring jar files for release 4.1.4
    class file will be generated under WEB-INF/classes folder

  • Pingback: Spring Data (JPA) – JUGLviv()

  • Rajputana Atul

    How can implement chaining of controllers?

  • David


    Works ok. I want to follow with the next tutorials so I have added just this:
    import javax.persistence.Entity;

    public class Shop {

    java.lang.IllegalStateException: ApplicationEventMulticaster not initialized – call ‘refresh’ before multicasting events via the context: WebApplicationContext for namespace ‘dispatcher-servlet’: startup date [Thu Jul 14 21:05:47 WEST 2016]; root of context hierarchy

    Any idea?

    • I’m not sure but try to define at least one field inside of the Shop class
      Very long time have not worked with Spring and Hibernate

  • Metrx Qin

    As a reminder, EL expr is disabled by default, which means ${message} will NOT be rendered properly.

    Remind to add isELIgnored=”false” to your page directive.