@RequestMapping
是 Spring MVC 中的一个注解,用于映射HTTP请求到控制器方法。它可以映射多个HTTP方法,或者在没有更具体的注解(如 @GetMapping
, @PostMapping
, 等)时使用。下面是一个示例:
javaimport org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
/**
* 这个方法将处理所有匹配 "/example" 的 HTTP GET 和 POST 请求
*/
@RequestMapping(value = "/example", method = {RequestMethod.GET, RequestMethod.POST})
public String handleExampleRequest() {
// 处理逻辑
return "This is an example response";
}
/**
* 如果没有更具体的注解,此方法将处理所有匹配 "/other" 的请求
*/
@RequestMapping("/other")
public String handleOtherRequest() {
// 处理逻辑
return "Handling other requests";
}
}
在上面的例子中,handleExampleRequest
方法会处理 /example
路径上的 GET 和 POST 请求。
handleOtherRequest
方法将处理所有匹配 /other
的请求,无论请求方法是什么(GET、POST、PUT等),因为没有指定 method
参数,所以默认匹配所有HTTP方法。
请注意,这里使用了 @RestController
注解,它是 @Controller
和 @ResponseBody
的组合,用于创建RESTful服务,自动将返回值转化为HTTP响应体。
REST(Representational State Transfer)是一种设计分布式系统的原则,尤其适用于Web服务。
外文名:Representational State Transfer,简称REST。
中文名:表现层状态转移。
属性:一种软件架构风格。(以Web为平台的。web服务的架构风格,前后端接口时候用到。)
REST之所以晦涩难懂,是因为前面主语(Resource )被去掉了。
全称是: Resource Representational State Transfer。
通俗来讲就是:资源在网络中以某种表现形式进行状态转移。
分解开来讲解:
Resource:资源,即数据(这是网络的核心);
Representational:某种表现形式,比如用JSON,XML,JPEG等;
State Transfer:状态变化。通过HTTP的动词(get查询、post新增、put修改、delete删除)实现。
@GetMapping
@GetMapping("/example")
public String handleGetRequest() {
// 处理逻辑
return "This is a GET request response";
}
@PostMapping
@PostMapping("/example")
public ResponseEntity<String> handlePostRequest(@RequestBody MyObject requestObject) {
// 处理逻辑
HttpHeaders headers = new HttpHeaders();
headers.add("Custom-Header", "Value");
return ResponseEntity.ok("Data received and processed");
}
@PutMapping
@PutMapping("/example/{id}")
public String handlePutRequest(@PathVariable Long id, @RequestBody UpdateObject updateObject) {
// 更新逻辑
return "Resource with ID " + id + " updated";
}
@DeleteMapping
@DeleteMapping("/example/{id}")
public String handleDeleteRequest(@PathVariable Long id) {
// 删除逻辑
return "Resource with ID " + id + " deleted";
}
@PatchMapping
@PatchMapping("/example/{id}")
public String handlePatchRequest(@PathVariable Long id, @RequestBody PartialUpdateObject partialUpdate) {
// 部分更新逻辑
return "Partial update applied to resource with ID " + id;
}
这些注解极大地简化了Spring应用中RESTful服务的实现,提高了开发效率和代码的可读性,同时遵循了Web服务的最佳实践。
@RequestParam
/search?query=keyword
,可以用@RequestParam
来绑定这些参数到方法参数上。java @GetMapping("/search")
public List<Item> searchItems(@RequestParam String query) {
// 使用query参数执行搜索逻辑
return itemService.findByKeyword(query);
}
@PathVariable
/users/{userId}
),@PathVariable
用于从URI模板中提取这些变量值。它使得每个资源实例都能通过其ID直接访问。java @GetMapping("/users/{userId}")
public User getUserById(@PathVariable Long userId) {
// 根据userId获取用户信息
return userService.findById(userId);
}
@RequestBody
java @PostMapping("/users")
public User createUser(@RequestBody User newUser) {
// 创建新用户并保存
return userService.save(newUser);
}
@ResponseBody
@RestController
配合使用,使得控制器方法无需视图解析,直接返回数据给客户端。java @RestController
public class UserController {
// ...
@GetMapping("/users/{userId}")
public User getUserById(@PathVariable Long userId) {
return userService.findById(userId);
}
// ...
}
@HeaderParam
@RequestHeader
代替):java @GetMapping("/secure-endpoint")
public String secureEndpoint(@RequestHeader("Authorization") String authToken) {
// 验证authToken
return "Secure content";
}
@CookieValue
java @GetMapping("/welcome")
public String welcomePage(@CookieValue("sessionToken") String token) {
// 使用token进行用户会话验证
return "Welcome!";
}
这些注解是构建RESTful Web服务时处理请求和响应数据的关键工具,它们帮助开发者高效地实现客户端与服务器之间的数据交换。