In the previous posts about Spring Boot (Part 01 e Part 02), some people asked me about Spring MVC because they did not know how it works. In this post, I will not teach how to configure Spring MVC, but rather give an overview of the main features.
What it is?
Spring MVC is a Spring web framework and action-based that works with MVC architecture (Model-View-Controller) and it helps in building flexible and loosely coupled web applications, besides being easy to use.
Example of use (calling a page)
@Controller
public class UserController {
@RequestMapping(value="/", method=RequestMethod.GET)
public String index() {
return "home";
}
}
Example of use (REST)
@RestController
public class UserRestController {
@RequestMapping(value="/users", method=RequestMethod.GET)
public List<User> listUsers() {
//... get users
return users;
}
}
Main things to know
@Controller
- It is the main annotation to define a class as a Spring MVC Controller. The Controller is responsible for mapping and receiving requests sent by the client.
@RestController
- Defines a class as a Spring MVC REST Controller. The main difference for @Controller is that the RestController does not look for a page when returning a value, but returns exactly that value.
- Example: When returning the String: “ralph”, the @Controller would look for a file (HTML, JSP, or any configured format) with that name. The @RestController would return exactly “ralph”.
@RequestMapping
- Main annotation to define mappings. In it is defined the HTTP method to be used, which Path to call, what will be the accepted data type and the return type of the content.
- Examples:
@RequestMapping(value="/users", method=RequestMethod.GET)
public String somePath() { /*code*/ }
@RequestMapping(value="/users", method=RequestMethod.POST,
consumes=MediaType.APPLICATION_JSON_VALUE,
produces=MediaType.APPLICATION_JSON_VALUE )
public String someOtherPath(User user) { /*code*/ }
Continue reading →