Getting Started

Defining Controller

Define your controller class with help of @Controller annotation. The @Controller annotation indicates that a particular class serves the role of a controller. Use @RequestMapping annotation to map controller class and its methods to a URL. The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method. This mapped urls will be used to send request from browser to the controller.

Here Welcome class is annotated by @Controller annotation and mapped with \Welcome url. Method display() is mapped with GET method and receives Model object as the parameter. Method display() is called when GET request is sent to URL \Welcome.

Model is a map object that contains data in form of key and value pair. Model carries data from Controller to View. View gets data from Model using keys and displays them using JSTL and other Spring tags. Here Model carries "message" from Controller to View.

Method display() returns View name. View name is resolved by ViewResolver as per bean definition in sunraysweb-servlet.xml. View name "Welcome" will be resolved as \WEB-INF\pages\Welcome.jsp.

Likewise submit() method is mapped with POST method. When POST request is sent submit() method will be called.

@Controller

@RequestMapping(value = "/Welcome")

public class WelcomeCtl {

@RequestMapping(method = RequestMethod.GET)

public String display(Model model) {

System.out.println("I am in display");

model.addAttribute("message", "Welcome to Spring MVC!!");

return "Welcome";

}

@RequestMapping(method = RequestMethod.POST)

public String submit(Model model) {

System.out.println("I am in submit");

model.addAttribute("message", "You sent post request!");

return "Welcome";

}

}

Creating JSP View

Spring MVC supports different types of views for different presentation technologies that includes JSPs, HTML, PDF, Excel worksheets, XML, Velocity templates, XSLT, JSON, Atom and RSS feeds, JasperReports etc. But most commonly we use JSP templates written with JSTL.

Here is Welcome.jsp. This View is resolved by ViewResolver as /WEB-INF/pages/Welcome.jsp. View gets value stored against "message" key in Model object and displays value using JSTL ( ${..} ) tag.

<html>

<head>

<title>Hello Spring MVC</title>

</head>

<body>

<h2>${message}</h2>

</body>

</html>

Here ${message} is the model attribute which we had added from controller using model.addAttribute() method. You may add more attributes in model to display at View.

Send a Request to Controller

Now your Controller is ready. Open a browser and send a request to controller using http://localhost:8080/STMavenSpringMVC/Welcome URL and you will see following screen.