Preparing for Java Interview?

My books Grokking the Java Interview and Grokking the Spring Boot Interview can help

Download PDF

Sunday, October 10, 2021

Difference between @RequestMapping and @GetMapping in Spring MVC? Example

Hello Java programmers, if you are wondering what is the difference between @RequestMapping and @GetMapping annotation in Spring MVC and when and how to use them then you have come to the right place. Earlier, I have shared the best Spring MVC courses and books, and In this tutorial, we are going to discuss spring and spring boot web services. In there, most of the interviewers asked about the difference between @RequestMapping and @GetMapping annotations in spring applications. Before going to discuss the difference between these annotations, first, understand what is @RequestMapping?, How do we use the @RequestMapping?, What is a request? and types of them.

Each annotation is meant to handle the relevant incoming request method type, as seen by the naming convention. It may appear that the @RequestMapping and @GetMapping methods are the same, but they are not. 

When it comes to @RequestMapping, it will demonstrate that it is used to generic request handler where we may use with GET, POST, PUT, or any other request methods utilizing the method attribute in Spring 4.3 new mapping annotations.

First, have a look at what is @RequestMapping and what our use cases are with a simple example. @RequestMapping is one of the most common annotations used in Spring Web applications. This annotation maps HTTP requests to handler methods of MVC and REST controllers.




1. What is @RequestMapping Annotation? Example

This is one of the basic annotations in Spring that maps HTTP requests with methods. This is used to map the request into the specific method in Spring.

@RequestMapping("/")
public void requestMapping() {
    return "Hello !";
}

The method is run every time an end-user makes an HTTP request. The mapping can also be done at the method or class level.

@RequestMapping("/student")
public class AdminController() {
    @RequestMapping("/addstudent")
    public String addStudent() {
        return "addStudent.html";
    }

    @RequestMapping("/getallstudent")
    public String getStudents() {
        return "getStudent.html";
    }

}

From here, the /student is assigned on the class level. And each method has separate mappings and this allows to have a prefix before creating the mapping.

The method attribute in the request method allows you to narrow down the request method to a specific request method. (GET, POST, PUT, DELETE, etc)

@Autowired
StudentRepository studentRepository;

@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(@ModelAttribute("student") Student student) {
    studentRepository.save(student);
}


The @ReqeustMapping annotation allows you to rely on the path variables to showcase a specific student, profile, grade, etc. as an example student/IT175644 this allows getting the specific student.

@Autowired
StudentRepository studentRepository;

@RequestMapping("/viewStudent/{studentId}")
public String viewStudent(@PathVariable int studentId, Model model) {
    Student student = studentRepository.getStudentById(studentId);
    model.addAttribute("student", student);
    return "viewStudent";
}


Many applications rely on request parameters to alter the state of the page. You can also use @RequestParam annotation to bind a request parameter to a variable.

@RequestMapping("/login")
public String login(@RequestParam(value = "error", required = false) String error, 
   @RequestParam(value = "logout", required = false) String logout, Model model) {

    if (error != null) {
        model.addAttribute("error", "Wrong username or password!");
    }
    if (logout != null) {
        model.addAttribute("msg", "You have successfully logged out!");
    }
    return "login";
}







2. What is @GetMapping Annotation? Example

HTTP GET requests are mapped to appropriate handler methods using the Spring @GetMapping annotation. The @GetMapping annotation assigns specified handler methods to HTTP GET requests. @RequestMapping(method = RequestMethod.GET) is a constructed annotation that serves as a shorthand for @RequestMapping(method = RequestMethod.GET).


@GetMapping - shortcut for @RequestMapping(method = RequestMethod.GET)

In the below example, the @GetMapping annotation mapping HTTP GET "/employees" and "/employees/{id}" requests onto specific handler methods getAllEmployees and getEmployeeById:


@Autowired
StudentRepository studentRepository;


@GetMapping("/students/{id}")
public ResponseEntity < Students > getEmployeeById( 
                    @PathVariable(value = "id") Long studentId)
throws ResourceNotFoundException {
    Students student = studentRepository.findById(studentId)
        .orElseThrow(() - > new ResourceNotFoundException("Student not found 
                                  for this id :: " + studentId));
    return ResponseEntity.ok().body(Students);
}





Difference between @RequestMapping and @GetMapping in Spring MVC?

With sprint Spring 4.3. and up things have changed. Now can use the @GetMapping methods that will handle the HTTP requests. The class-level @RequestMapping specification is refined with the (method-level)@GetMapping annotation.

  • @RequestMapping is a class level
  • @GetMapping is a method-level

The @RequestMapping annotation is used to map web requests to specific handler classes and functions. This annotation's key advantage is that it may be used on both the controller class and methods. @RequestMapping is typically thought of as a class-level annotation. With the help of method level, get mapping, @Requestmapping is fine-tuned.

It is always advised to be specific while declaring @RequestMapping on the controller methods as in most mapping handler classes, @Getmapping is not used. This feature distinguishes the @Getmapping and @RequestMapping annotations. 

It's an annotation that serves as a shortcut for the @Requestmapping annotation. Request handler pathways are mapped to specified handler methods. In comparison to @Requestmapping, there are fewer lines of code.

@Getmapping("/peson/{personId}")

By default, the entire requests are assumed to be originated from the HTTP Get type.

This is how Craig Walls describe the difference between @RequestMapping and @GetMapping in Spring in Action, Fifth Edition.

Difference between @RequestMapping and @GetMapping in Spring MVC? Example



So this is all about the difference between @RequestMapping and @GetMapping in Spring MVC and REST. @RequestMapping is used at the class level while @GetMapping is used to connect the methods. This is also an important Spring MVC interview question to knowing how and when to use both RequestMapping and GetMapping is crucial for Java developers. 

See you in the next tutorial with a more interesting topic.

Other Java and Spring Tutorial you may like
  • How Spring MVC works internally? (answer)
  • Spring Data JPA @Query Example (query example)
  • Spring Data JPA Repository (JpaReposistory example)
  • 5 Courses to learn Spring Cloud for Microservices (courses)
  • 20+ Spring MVC Interview Questions for Programmers (answer)
  • Difference between @Autowired and @Inject in Spring? (answer)
  • 5 Courses to Learn Spring Security for Java programmers (courses)
  • Top 5 Spring Boot Annotations Java Developers should know (read)
  • Difference between @RequestParam and @PathVariable in Spring (answer)
  • Top 7  Courses to learn Microservices in Java (courses)
  • 10 Spring MVC annotations Java developer should learn (annotations)
  • @SpringBootApplication vs @EnableAutoConfiguration? (answer)
  • 15 Spring Boot Interview Questions for Java Developers (questions)
  • Top 5 Courses to Learn and Master Spring Cloud (courses)
  • Top 5 Frameworks Java Developer Should Know (frameworks)
  • 10 Advanced Spring Boot Courses for Java developers (courses)
  • Top 5 Spring Cloud annotations Java programmer should learn (cloud)
  • Difference between @Component, @Service, and @Controller in Spring (answer)

Thanks for reading this article so far. If you find these differences between RequestMapping and GetMapping annotation in Spring MVC then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are a beginner and want to learn the Spring MVC from scratch, and looking for some free resources then you can also check out these free core Spring and Spring MVC courses for beginners. This list contains free Udemy and Pluralsight courses to learn Spring MVC from scratch >

No comments :

Post a Comment