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.

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



  SimpleController
  
  
    index.jsp
  
  

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"
    pageEncoding="ISO-8859-1"%>
...

Home page

This is a Home Page.

...

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

projects-structure-spring-mvc-beginning

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:

	
		3.1.1.RELEASE
	

	
		
		
			org.springframework
			spring-context
			${spring.version}
		
		
			org.springframework
			spring-webmvc
			${spring.version}
		
		
			org.springframework
			spring-beans
			${spring.version}
		
		
			org.springframework
			spring-web
			${spring.version}
		
		
		
			cglib
			cglib
			2.2.2
		
		
		
			javax.servlet
			javax.servlet-api
			3.0.1
			provided
		
		
			jstl
			jstl
			1.2
		
	

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 {
	
	@Bean
	public UrlBasedViewResolver setupViewResolver() {
		UrlBasedViewResolver resolver = new UrlBasedViewResolver();
		resolver.setPrefix("/WEB-INF/pages/");
		resolver.setSuffix(".jsp");
		resolver.setViewClass(JstlView.class);
		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 {
	
	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		
		AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
		ctx.register(WebAppConfig.class);
		
		ctx.setServletContext(servletContext);	
		
		Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
		servlet.addMapping("/");
		servlet.setLoadOnStartup(1);
		
	}

}

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"
    pageEncoding="ISO-8859-1"%>

...
    

Hello world: ${message}

Well done!

...

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.

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

@Controller
public class LinkController {

	@RequestMapping(value="/hello-page")
	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"
    pageEncoding="ISO-8859-1"%>
...

Home page

This is a Home Page.

Hello world link

...

The final project structure is:

final-projects-structure-spring-mvc-beginning

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

result-of-spring-mvc-beginning

Summary

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.

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
  • http://www.agung-setiawan.com Agung Setiawan

    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(SpringServletContainerInitializer.java:147)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5370)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown 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

    • http://fruzenshtein.com/ Alex Zvolinskiy

      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.

    • http://fruzenshtein.com/ Alex Zvolinskiy

      Is index page loading well?

  • my2 koseli

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

    Thanks

  • my2 koseli

    Hi,

    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

    Hi,

    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?

    • http://fruzenshtein.com/ Alex Zvolinskiy

      No
      This example doesn’t has a GitHub repo

  • 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

    • http://fruzenshtein.com/ Alex Zvolinskiy

      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

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

  • Khairul Padzli

    Try change to this instead
    @RequestMapping(“/hello-page”)

  • 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