Spring MVC @Controller Annotation Example

By Arvind Rai, April 19, 2015
In spring MVC, to create a controller class, spring provides @Controller annotation. This annotation is the specialization of @Component. Spring container will identify the controller class by classpath scanning. If we have created our controller in the package com.concretepage.controller then we need to assign this package with @ComponentScan("com.concretepage.controller ") in java config. We can be configure controller either by base package or by configuring individual controller. In our example we have configured base package. It means spring will scan that java package for controllers.

Create A Class using @Controller

To test the @Controller, we are creating a class which will be annotated with @Controller. We are creating a method that will serve the request for a specific URL pattern annotated by @RequestMapping.
package com.concretepage.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
public class HelloWorldController {
	public String createUser(@RequestParam("name") String name, ModelMap model) {
		model.addAttribute("name", name);
		return "success";

Configure Controller package in Java Config or Spring XML

In our demo we are using java config to configure bean. @Controller annotation is scanned by spring. So our class annotated with @Controller is available in spring container. Find the java configuration file.
package com.concretepage.config;  
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
public class AppConfig {  
    public UrlBasedViewResolver setupViewResolver() {  
        UrlBasedViewResolver resolver = new UrlBasedViewResolver();  
        return resolver;  
If we are using Spring XML, we can do it as
<context:component-scan base-package="com.concretepage.controller" /> 

Create a View Page

When the method in controller runs, our view page is displayed. Find the JSP.
<title> @Controller Demo </title>
	<h1>Hello :  ${name}</h1>


To check the output, run the URL http://localhost:8080/concretepage-1/testapp/hello?name=Ram
We will get the output.
Spring MVC  @Controller Annotation Example

Download Complete Source Code


©2023 concretepage.com | Privacy Policy | Contact Us