Spring MVC Annotations With Examples

@RequestParam

@RequestParam annotation is used to bind request parameters to a method parameter in your controller.

Parameters using this annotation are required by default, but you can specify that a parameter is optional by setting @RequestParam's required attribute to false (e.g., @RequestParam(value="id", required=false)).

@Controller @RequestMapping("/employee") @SessionAttributes("employee") public class EmployeeController { // ... @RequestMapping(method = RequestMethod.GET) public String getEmployee(@RequestParam("empId") int empId, ModelMap model) { //get Employee model.addAttribute("employee", employee); return "edit"; } }

We can assign the default value to the request params if the params are null.

@RequestMapping("/get") public List<Employee> getAll(@RequestParam(defaultValue = "10") int limit,@RequestParam(defaultValue = "0") int offset) { // ... List<Employee> empList = employeeService.getAll(limit,offset); return }

@PathVariable

Annotation which indicates that a method parameter should be bound to a URI template variable. Supported for RequestMapping annotated handler methods.

If the method parameter is Map then the map is populated with all path variable names and values.

It is introduced in the Spring in version 3.1.

@GetMapping("/employee/{id}") public String getEmployee(@PathVariable("id") String id) { // }

The variable name in the @PathVariable annotation is optional if the name of the part in the template matches the name of the method argument. above example, If we remove "id" from the @PathVariable annotation.

@GetMapping("/employee/{id}") public String getEmployee(@PathVariable String id) { // }

By Using "required = false" parameter to mark the path variable as an optional.

@GetMapping("/employee/{id}") public String getEmployee(@PathVariable(required = false) String id) { // }

@SessionAttribute

This annotation to bind a method parameter to a session attribute. The main use of @SessionAttribute is to provide convenient access to existing, permanent session attributes (e.g. user authentication object) with an optional/required check and a cast to the target method parameter type.

For use cases that require adding or removing session attributes consider injecting org.springframework.web.context.request.WebRequest or javax.servlet.http.HttpSession into the controller method.

For temporary storage of model attributes in the session as part of the workflow for a controller, consider using SessionAttributes instead.

It is introduced in the Spring in version 4.3

@GetMapping("/employee") public String getEmployee(@SessionAttribute(name = "id") String id) { // }

here we have id is used as SessionAttribute.

@RequestBody

Annotation indicating a method parameter should be bound to the body of the web request.

The body of the request is passed through an HttpMessageConverter to resolve the method argument depending on the content type of the request. Optionally, automatic validation can be applied by annotating the argument with @Valid. Supported for annotated handler methods.

It is introduced in the Spring in version 3.0

public class Employee { private String id; private String name; private String department; private String phone; private int age; //Getters and Setters } @RequestMapping(method=RequestMethod.POST, consumers= "application/json") public @ResponseBody Employee saveEmployee(@RequestBody Employee employee) { return employeeRepository.save(employee); }

@ResponseBody

Annotation that indicates a method return value should be bound to the web response body. Supported for annotated handler methods.This annotation is used to transform a Java object returned from the a controller to a resource representation requested by a REST client

As of version 4.0 this annotation can also be added on the type level in which case it is inherited and does not need to be added on the method level.

It is introduced in the Spring in version 3.0

@RequestMapping(method=RequestMethod.POST, consumers= "application/json") public @ResponseBody Employee saveEmployee(@RequestBody Employee employee) { return employeeRepository.save(employee); }

@InitBinder

Annotation that identifies methods which initialize the WebDataBinder which will be used for populating command and form object arguments of annotated handler methods.

Such init-binder methods support all arguments that RequestMapping supports, except for command/form objects and corresponding validation result objects. Init-binder methods must not have a return value; they are usually declared as void.

Typical arguments are WebDataBinder in combination with WebRequest or Locale, allowing to register context-specific editors.

It is introduced in the Spring in version 2.5

@InitBinder protected void initBinder(WebDataBinder binder) { binder.setValidator(customValidator); }

@RestController

A convenience annotation that is itself annotated with @Controller and @ResponseBody. Types that carry this annotation are treated as controllers where @RequestMapping methods assume @ResponseBody semantics by default.

@RestController is processed if an appropriate HandlerMapping-HandlerAdapter pair is configured such as the RequestMappingHandlerMapping-RequestMappingHandlerAdapter pair which are the default in the MVC Java config and the MVC namespace.

It is introduced in the Spring in version 4.0

@RestController class EmployeeControler{ @RequestMapping("/employee/{id}") public String hello(String id){ return employeeRepository.finfById(id); } }

You can see that there is no @ResponseBody annotation is required to generate a RESTful response. Before @RestController, We need to use @Controller on top of the class and annotated each handler method with @ResponseBody annotation.

In this article, we have seen Spring MVC Annotations With Examples.