Enterprise Java

Spring MVC: Creation of a simple Controller with Java based config

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="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_3_0.xsd" id="WebApp_ID" version="3.0">

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

<%@ 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.context.support.AnnotationConfigWebApplicationContext;
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.

Reference: Spring MVC: Creation of a simple Controller with Java based config from our JCG partner Alex Fruzenshtein at the Fruzenshtein’s notes blog.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Alexey Zvolinskiy

Alexey is a test developer with solid experience in automation of web-applications using Java, TestNG and Selenium. He is so much into QA that even after work he provides training courses for junior QA engineers.
Notify of

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

Newest Most Voted
Inline Feedbacks
View all comments
abhishek somani
10 years ago

nice one for beginners

Marcio Romualdo
10 years ago

You can config just one Spring dependence into pom.xml: “spring-webmvc”. :)

10 years ago

You right =)

Agung Setiawan
10 years ago

still prefer using xml for this simple configuration, maybe someday i will use it :D

Stuart Boston (@bostons)

I tried this with Spring 3.2 and it seems to have a problem with the new configuration.

9 years ago

how to create a controller with java code !

8 years ago
8 years ago
8 years ago

Nice blog written on “Spring MVC” which described information on the Creation of a simple Controller with Java based config. The information contained in the blog is very helpful for Java developers. Here is an another informative blog published on Spring MVC & MongoDB http://findnerd.com/list/view/Spring-MVC-and-MongoDB/2240/ , hope this will help developers too to understand the Spring MVC in a detailed way. While learning from this blog developers can also post & view java questions and answers to enhance the tech knowledge among the developers community.


SIddiqui Habib Ahmed
SIddiqui Habib Ahmed
5 years ago

how to create controller with java codes??

Back to top button