Spring MVC basics – 1st chapter

The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale, time zone and theme resolution as well as support for uploading files. The default handler is based on the @Controller and @RequestMapping annotations, offering a wide range of flexible handling methods. With the introduction of Spring 3.0, the @Controller mechanism also allows you to create RESTful Web sites and applications, through the @PathVariable annotation.

In Spring’s approach to building web sites, HTTP requests are handled by a controller identified by the @Controller annotation.

The following example show how a java class has been marked as controller:

package jtrainer.education.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class TemperatureController {

@RequestMapping("/setTemperature")
public String setTemperature(@RequestParam(value="gatewayId", required=true) String id, Model model) {
model.addAttribute("id", id);
//make some business logic here
return "temperature set";
}

}

The @RequestMapping annotation ensures that HTTP requests to /setTemperature are mapped to the setTemperature() method.

As we did not specify the HTTP methos e.g. GET vs. PUT, POST, and so forth, then @RequestMapping maps all HTTP operations by default.

Use @RequestMapping(method=GET) to narrow this mapping.

@RequestParam binds the value of the query String parameter gatewayId into the name parameter of the setTemperature() method. This query String parameter is required (required=true); if it is absent in the request, this would generate an error. The value of the name parameter is added to a Model object, ultimately making it accessible to the view template.

The implementation of the method body relies on a view technology. We will cover this later.

Leave a Reply

Your email address will not be published. Required fields are marked *