7 Vital Spring MVC & REST Annotations For Java Devs
7 Vital Spring MVC & REST Annotations For Java Devs
1@Controller
2@RequestMapping
3@PathVariable
4@RequestParam
5@RequestBody
@ResponseBody
6@GetMapping
@PostMapping
7@Valid
This annotation is used to make
a class as a web controller,
which can handle client
requests and send a response
back to the client. This is a
class-level annotation, which is
put on top of your controller
class. Similar to @Service and
@Repository it is also a
stereotype annotation. If you
are wondering what is the
difference between them then
you can also see this article to
learn more about their
differences.
Here is an example of @Controller
annotation in Spring MVC:
@Controller
public class MyController {
@RequestMapping("/greet")
public String greet() {
return "welcome";
}
}
Example
Explantion
Here, when someone
accesses the URL
"/greet", the greet()
method in the
MyController class will
be called. The method's
return value, in this
case, is "welcome",
which could correspond
to a view template.
3. PathVariable
Imagine URLs as
paths, and
sometimes these
paths have
dynamic parts –
like variables. The
@PathVariable
annotation helps
you pick up these
variables and use
them in your
method.
Example
@Controller
public class UserController {
@RequestMapping("/user/{id}")
public String getUser(@PathVariable int id) {
// Fetch user data using 'id'
return "userDetails";
}
}
Example
@Controller
public class SearchController {
@RequestMapping("/search")
public String search(@RequestParam String
query) {
// Perform a search using 'query'
return "searchResults";
}
}
Example Explantion
If someone accesses "/search?
query=apple", the search() method
will receive "apple" as the value of
the query parameter. This is similar
to grabbing data from a form.
This covers the first four annotations,
making them easier to understand
with relatable examples.
5. Request Body &
Response Body
Think of these
annotations as
packaging and
unpackaging data. When
a client sends data to
your server (like a JSON
object), @RequestBody
converts it into a Java
object that your code
can work with. And
when your code
generates data to send
back to the client,
@ResponseBody
converts it into the
necessary format (like
JSON) for the client to
understand.
Example:-
@RestController
public class ApiController {
@PostMapping("/create")
public ResponseEntity<String>
create(@RequestBody Item item) {
// Process 'item' and respond
return ResponseEntity.ok("Item created");
}
}
Consider these
annotations as
shortcuts for mapping
HTTP methods to URLs.
Instead of using
Request-Mapping with
specific HTTP methods,
you can use
@GetMapping for GET
requests and
@PostMapping for
POST requests.
Example:-
@Controller
public class ShortcutController {
@GetMapping("/welcome")
public String welcome() {
return "greeting";
}
}
Here, the
welcome()
method is
mapped to the
URL "/welcome"
and will respond
to GET requests.
It's a cleaner and
more focused
way to specify
the intended
HTTP method.
7.Valid &
Model-Attribute
Think of @Valid as your
application's spellchecker. It
ensures the data coming in adheres
to specific rules or constraints. And
@ModelAttribute is like your
assistant, organizing and passing
the validated data to your method.
Example:-
@Controller
public class FormController {
@PostMapping("/submit")
public String submitForm(@Valid
@ModelAttribute UserData userData,
BindingResult result) {
if (result.hasErrors()) {
return "errorPage";
}
// Process 'userData' and return
success
return "successPage";
}
}
Example Explantion
In this snippet, the @Valid annotation
ensures the incoming UserData follows
the specified rules. If there are errors, it
redirects to an error page. If the data is
valid, the @ModelAttribute passes the
organized data to the submitForm()
method for further processing.