DEV Community

Cover image for Spring - @RequestMapping
Yiğit Erkal
Yiğit Erkal

Posted on

4 2

Spring - @RequestMapping

TL;DR

It is used to map web requests to Spring Controller methods.

In Spring Web applications, @RequestMapping is one of the most used annotations. HTTP requests are mapped to MVC and REST controller handler methods with this annotation.

URL handler using @RequestMapping annotation as it follows here:

@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
Enter fullscreen mode Exit fullscreen mode

The alternative approach in other words possible short version is:

@GetMapping("/get/{id}")
Enter fullscreen mode Exit fullscreen mode

We can also implement other mappings mentioned below:

RequestMapping Spring Annotation

To sum up, it is a better approach to use RequestMapping or alternative mapping in class level controllers since all your requests and responses will be handled in controller. Here is a full code example:

@Controller
@RequestMapping(value = "/orders", method = RequestMethod.GET)
public class DemoController {


  @RequestMapping(value = "/{orderId}", method = RequestMethod.GET)
  @ResponseBody
  public String getOrder(@PathVariable final String orderId) {
    return "Order ID: " + orderId;
  }

  @RequestMapping(value = "/addProduct", method = RequestMethod.POST)
  public String addProductPost(@ModelAttribute("product") 
Product product) {
    // some code
}

 // other mappings
 // ...
}
Enter fullscreen mode Exit fullscreen mode

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay