Tags

,

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*/ }

  • It is worth mentioning that, in the method someOtherPath above, a parameter received is a User, a class of our model. In the case of a page and a form, it is enough that the name attribute of the input (regardless of whether text, textarea, combobox, etc.) is equal to the attribute of the user. Example:
<form method="POST" action="/users">
    <input type="text" name="name"/>
    <input type="text" name="city"/>
    <input type="submit" value="Create"/>
</form>
  • Thus, it is enough that the User has the attributes ‘name’ and ‘city’ and Spring MVC automatically fills these values in the User object.

@RequestBody

  • Para que o exemplo do método someOtherPath acima funcione em uma requisição REST, eu preciso indicar para o Spring MVC o corpo da requisição. Pra isso, utiliza a anotação @RequestBody. Sendo assim, basta que o json/xml/etc. passado também tenha esses atributos. Example:
  • In order for the example of the above someOtherPath method to work on a REST request, I need to indicate to the Spring MVC the request body. To do this, use the @RequestBody annotation. So, make sure that your json/xml/etc. also have these attributes.
@RequestMapping(value="/users", method=RequestMethod.POST, 
 consumes=MediaType.APPLICATION_JSON_VALUE,
 produces=MediaType.APPLICATION_JSON_VALUE )
public String someOtherPath(@RequestBody User user) { /*code*/ }
{
    "name": "Someone",
    "city": "Calgary"
}

@Valid

  • With this annotation and what was seen above, I can use JSR-303 validations (@NotNull, @Min, @Max, etc …) to validate the data being passed. To do this, simply use the JSR-303 annotations in the User object with the desired validations, and use the @Valid annotation in the Controller.
@RequestMapping(value="/users", method=RequestMethod.POST, 
 consumes=MediaType.APPLICATION_JSON_VALUE,
 produces=MediaType.APPLICATION_JSON_VALUE )
public String someOtherPath(@RequestBody @Valid User user) { /*code*/ }

Model

  • This is not an annotation, but an object that all Controller methods can have. Just set it in the method that it is already injected by Spring. The Model basically serves to add attributes to be used on the page. Example:
@RequestMapping(value="/", method=RequestMethod.GET)
public String index(Model model) {
    //get user
    model.addAttribute("user", user);
    return "home";
}
  • Example on HTML with Thymeleaf:
<p>User <span th:text="${user.name}"/> added with success.</p>

@PathVariable

  • Sometimes we need to get some parameter that was defined on URL, for example: /users/1. WE WANT THIS 1. For that, we can use @PathVariable. Example:
@RequestMapping(value="/users/{id}", method=RequestMethod.GET)
public User getById(@PathVariable("id") Integer userId) { /*code*/ }

@RequestParam

  • And sometimes we need to get some parameter that was defined by query parameter on URL, for example: /users?name=ABC. For that, we can use @RequestParam. Example:
@RequestMapping(value="/users", method=RequestMethod.GET)
public User user(@RequestParam("name") String name) { /*code*/ }

I have a project that shows almost everything that was commented, take a look: https://github.com/ralphavalon/java-sample-project

Thank you.

Advertisements