0% found this document useful (0 votes)
20 views19 pages

7 Vital Spring MVC & REST Annotations For Java Devs

1. @Controller marks a class as a web controller to handle client requests and responses. 2. @RequestMapping maps URLs to controller methods. When a URL is accessed, the associated method executes. 3. @PathVariable extracts variable parts of URLs to pass as method parameters. 4. @RequestParam extracts query parameters from URLs to pass as method parameters.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
20 views19 pages

7 Vital Spring MVC & REST Annotations For Java Devs

1. @Controller marks a class as a web controller to handle client requests and responses. 2. @RequestMapping maps URLs to controller methods. When a URL is accessed, the associated method executes. 3. @PathVariable extracts variable parts of URLs to pass as method parameters. 4. @RequestParam extracts query parameters from URLs to pass as method parameters.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 19

Unlocking the Power

of Spring MVC and


REST: 7 Must-Know
Java Annotation
Techniques
Spring MVC Annotation

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:

@Controllerpublic class HelloController{


// handler methods
}

In this example, the


HelloController class is
ready to process
incoming HTTP requests
and provide appropriate
responses. You don't
need to follow any special
class hierarchy or
interfaces – just annotate
the class.
2.RequestMapping
Think of RequestMapping as
the road sign that directs
traffic. It's used to link URLs to
specific methods within a
controller. When a particular
URL is accessed, the associated
method gets executed.
Example:-

@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";
}
}

In this case, when a


URL like "/user/123"
is accessed, the
getUser() method
will receive the value
"123" for the id
parameter. This
allows you to fetch
user data based on
the provided ID.
4.RequestParam
Ever seen URLs with question marks
followed by parameters? These are
query parameters. @RequestParam
helps you grab these parameters for
further processing.

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");
}
}

In this example, when a client


sends a request with a JSON object
representing an item, the create()
method uses @RequestBody to
convert it into a Java object (Item).
After processing, the method uses
@ResponseBody to send back a
response like "Item created" in a
format the client can understand.
6. Get-Mapping &
Post-Mapping

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.

You might also like