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

What are the differences between @RequestParam and @PathVariable?

Câu trả lời

In Spring MVC, the annotations @RequestParam and @PathVariable are used to extract data from the URL of an HTTP request, but they serve different purposes and are used in different contexts.

@RequestParam

@RequestParam is used to extract query parameters from the URL. These parameters are typically appended to the URL after a question mark (?) and are represented as key-value pairs. This annotation is particularly useful in scenarios where you need to filter or sort data based on parameters provided by the client. For example, in a URL like /users?name=John, @RequestParam can be used to retrieve the value of name.

Key characteristics of @RequestParam include:

  • It binds a method parameter to a query parameter.
  • It is optional and can have a default value if not present in the request.
  • It is commonly used in web applications where data is passed as query parameters[1][3][4].

@PathVariable

@PathVariable, on the other hand, is used to extract values from the URI path itself. This is useful in RESTful web services where URL patterns often include values that identify specific resources. For example, in a URL like /users/123, @PathVariable can be used to extract the 123 as a user ID directly from the path.

Key characteristics of @PathVariable include:

  • It binds a method parameter to a template variable in the URI path.
  • It is required by default, and if the corresponding URI variable is not present in the request, it can lead to an error.
  • It is ideal for RESTful services where the URL contains values that are part of the URI[1][3][4].

Practical Usage

In practical terms, @RequestParam is more flexible as it does not affect the URL structure and can handle multiple values for the same parameter name. It is also ideal for handling form data in traditional web applications. @PathVariable is crucial for RESTful services where the URL path elements are used to specify the resources, and ...

middle

middle

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

middle

What is Bean Factory?

junior

What is Application Context?

middle

How do you define a bean scope?

Bình luận

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

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