Câu hỏi phỏng vấn Spring
Câu hỏi

Explain @RequestMapping annotation.

Câu trả lời

The @RequestMapping annotation in Spring MVC is a fundamental tool used for mapping web requests to specific handler methods within controller classes. This annotation is versatile and can be applied at both the class and method levels, allowing for flexible handling of HTTP requests in a Spring MVC application.

Basic Concept and Usage

@RequestMapping is used to map URLs to controller methods. It helps in directing incoming web requests to the appropriate handler functions based on the URL path, HTTP method, and other request parameters. When applied at the class level, it defines a basic or root path, and when specified at the method level, it provides further specification that builds upon the base path defined at the class level.

Handling HTTP Methods

The annotation supports various HTTP methods like GET, POST, PUT, DELETE, etc., through its method attribute. This allows developers to handle different types of client requests under the same URL pattern but with different methods. For example, you might have one method in a controller handle GET requests for retrieving data, while another handles POST requests for submitting data.

@Controller
@RequestMapping("/products")
public class ProductController {

    @RequestMapping(method = RequestMethod.GET)
    public String getAllProducts() {
        // Method implementation
        return "products";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String addProduct(Product product) {
        // Method implementation
        return "redirect:/products";
    }
}

Advanced Mappings

@RequestMapping can also handle more complex scenarios such as mapping requests based on header values, request parameters, or producing specific content types. This is useful for creating APIs that respond differently based on a...

junior

junior

Gợi ý câu hỏi phỏng vấn

expert

What's the difference between @Component, @Repository & @Service annotations in Spring?

senior

What is the default scope in the web context?

expert

What are some of the best practices for Spring Framework?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào