请求映射的核心:@requestmapping 注解
@requestmapping 是 spring mvc 中最核心、最通用的映射注解。它可以用于类级别(class-level)和方法级别(method-level)。
类级别映射 (class-level mapping):
- 当
@requestmapping应用在类上时,它定义了controller 处理所有请求的基类url 路径。 - 这样可以避免在每个方法上添加重复相同的路径前缀。
- 当
方法级别映射 (method-level mapping):
- 当
@requestmapping应用在方法上时,它指定了该方法具体处理哪个(或哪些)url 路径的请求。 - 这个路径是相对于类级别路径的(如果存在的话)。
- 当
@requestmapping 的主要属性:
value或path:- 指定映射的 url 路径。可以是一个字符串数组,表示映射多个路径到同一个方法。
- 支持 ant 风格的路径模式(如
*,**,?)和 uri 模板变量(路径变量,如{userid})。 value和path是同义词,可以互换使用。
method:- 指定该方法处理的 http 请求方法(get, post, put, delete, patch, options, head, trace)。
- 可以是一个
requestmethod枚举值的数组,表示处理多种 http 方法。 - 如果不指定,默认会匹配 所有 http 方法。
params:- 根据请求参数(query parameters 或 form data)进行映射。只有当请求中包含(或不包含,或具有特定值)指定的参数时,才会匹配成功。
- 表达式语法:
"myparam": 参数myparam必须存在。"!myparam": 参数myparam必须不存在。"myparam=myvalue": 参数myparam必须存在且值为myvalue。"myparam!=myvalue": 参数myparam必须存在且值不为myvalue。- 可以组合多个条件,如
{"myparam=val", "otherparam"}(and 关系)。
headers:- 根据请求头(request headers)进行映射。只有当请求包含(或不包含,或具有特定值)指定的头信息时,才会匹配成功。
- 语法与
params类似,如"accept=application/json","!user-agent","x-custom-header=value"。
consumes:- 指定该方法能够处理的请求的
content-type(即客户端发送的数据类型)。只有当请求的content-typeheader 与指定的值匹配时,才会映射成功。 - 例如:
consumes = "application/json"或consumes = mediatype.application_json_value。可以指定多个,如{"application/json", "application/xml"}。
- 指定该方法能够处理的请求的
produces:- 指定该方法能够生成的响应的
content-type(即服务器返回的数据类型)。spring 会根据请求的acceptheader 和此属性进行内容协商(content negotiation),选择最合适的httpmessageconverter来序列化返回值。 - 例如:
produces = "application/json"或produces = mediatype.application_json_value。可以指定多个。
- 指定该方法能够生成的响应的
示例:使用 @requestmapping
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.mediatype;
@controller
@requestmapping("/users") // 类级别映射,所有方法都在 /users 路径下
public class usercontroller {
// 映射 get /users/{id}
@requestmapping(value = "/{id}", method = requestmethod.get, produces = mediatype.application_json_value)
@responsebody // 如果用 @controller 需要加这个来返回数据
public user getuser(@pathvariable long id) {
// ... 获取用户逻辑 ...
return new user(id, "example user");
}
// 映射 post /users
@requestmapping(method = requestmethod.post, consumes = mediatype.application_json_value)
@responsebody
public string createuser(@requestbody user newuser) {
// ... 创建用户逻辑 ...
return "user created";
}
// 映射 get /users?admin=true (需要 admin 参数)
@requestmapping(method = requestmethod.get, params = "admin=true")
@responsebody
public string getadminusers() {
// ... 获取管理员用户列表 ...
return "list of admin users";
}
// 映射 get /users (只接受 json 请求)
@requestmapping(method = requestmethod.get, headers = "accept=application/json")
@responsebody
public string getusersacceptingjson() {
// ... 获取用户列表 ...
return "list of users (json requested)";
}
}
@requestmapping 的变体 (快捷方式注解)
为了提高代码的可读性和简洁性,spring 提供了针对特定 http 方法的快捷方式注解。它们本质上是 @requestmapping 预设了 method 属性的别名。
@getmapping: 映射 http get 请求。等价于@requestmapping(method = requestmethod.get)。@postmapping: 映射 http post 请求。等价于@requestmapping(method = requestmethod.post)。@putmapping: 映射 http put 请求。等价于@requestmapping(method = requestmethod.put)。@deletemapping: 映射 http delete 请求。等价于@requestmapping(method = requestmethod.delete)。@patchmapping: 映射 http patch 请求。等价于@requestmapping(method = requestmethod.patch)。
这些快捷注解也支持 @requestmapping 的 value/path, params, headers, consumes, produces 属性。
使用快捷方式注解的优点:
- 更简洁: 代码更短。
- 更清晰: 一眼就能看出方法处理的是哪种 http 请求。
示例:使用快捷方式注解 (@restcontroller 简化)
import org.springframework.web.bind.annotation.*;
import org.springframework.http.mediatype;
@restcontroller // 使用 @restcontroller,无需在每个方法上加 @responsebody
@requestmapping("/api/items") // 类级别映射
public class itemcontroller {
// 映射 get /api/items/{itemid}
// produces 也可直接写字符串
@getmapping(value = "/{itemid}", produces = mediatype.application_json_value)
public item getitem(@pathvariable string itemid) {
// ... 获取物品逻辑 ...
return new item(itemid, "sample item");
}
// 映射 post /api/items
// consumes 可以指定多个
@postmapping(consumes = {mediatype.application_json_value, mediatype.application_xml_value})
public string createitem(@requestbody item newitem) {
// ... 创建物品逻辑 ...
return "item created: " + newitem.getname();
}
// 映射 put /api/items/{itemid}
@putmapping("/{itemid}")
public item updateitem(@pathvariable string itemid, @requestbody item updateditem) {
// ... 更新物品逻辑 ...
updateditem.setid(itemid); // 假设更新成功
return updateditem;
}
// 映射 delete /api/items/{itemid}
@deletemapping("/{itemid}")
public string deleteitem(@pathvariable string itemid) {
// ... 删除物品逻辑 ...
return "item deleted: " + itemid;
}
// 映射 get /api/items?type=gadget
@getmapping(params = "type=gadget")
public string getgadgets() {
return "list of gadgets";
}
// 映射 get /api/items (需要特定 header)
@getmapping(headers = "x-api-version=2")
public string getitemsv2() {
return "list of items (api v2)";
}
}
// 示例 pojo
class item {
private string id;
private string name;
// constructors, getters, setters...
public item(string id, string name) { this.id = id; this.name = name; }
public string getid() { return id; }
public void setid(string id) { this.id = id; }
public string getname() { return name; }
public void setname(string name) { this.name = name; }
}
class user {
private long id;
private string username;
// constructors, getters, setters...
public user(long id, string username) { this.id = id; this.username = username; }
public long getid() { return id; }
public string getusername() { return username; }
}
总结
@requestmapping是基础,可以映射任何 http 方法,并提供最全面的配置选项(path,method,params,headers,consumes,produces)。@getmapping,@postmapping,@putmapping,@deletemapping,@patchmapping是针对特定 http 方法的快捷方式,使代码更简洁明了,是目前 spring mvc/webflux 开发中的推荐用法。- 可以在类级别和方法级别同时使用映射注解,类级别定义基础路径,方法级别定义相对路径。
- url 路径通过
value或path属性匹配,支持模式和路径变量 ({var})。 - http 方法通过
method属性(在@requestmapping中)或选择特定的快捷注解(如@getmapping)来匹配。 - 请求参数通过
params属性进行匹配。 - 请求头通过
headers属性进行匹配。 - 请求体类型 (
content-type) 通过consumes属性进行匹配。 - 可接受的响应类型 (
accept) 通过produces属性参与内容协商。
以上就是spring mvc映射http请求到controller的处理方法的详细内容,更多关于spring mvc映射http到controller的资料请关注代码网其它相关文章!
发表评论