当前位置: 代码网 > it编程>编程语言>Java > Spring MVC映射HTTP请求到Controller的处理方法

Spring MVC映射HTTP请求到Controller的处理方法

2025年05月21日 Java 我要评论
请求映射的核心:@requestmapping注解@requestmapping是 spring mvc 中最核心、最通用的映射注解。它可以用于类级别(class-level)和方法级别(method

请求映射的核心:@requestmapping 注解

@requestmapping 是 spring mvc 中最核心、最通用的映射注解。它可以用于类级别(class-level)和方法级别(method-level)。

  1. 类级别映射 (class-level mapping):

    • 当 @requestmapping 应用在类上时,它定义了controller 处理所有请求的基类url 路径。
    • 这样可以避免在每个方法上添加重复相同的路径前缀。
  2. 方法级别映射 (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-type header 与指定的值匹配时,才会映射成功。
    • 例如:consumes = "application/json" 或 consumes = mediatype.application_json_value。可以指定多个,如 {"application/json", "application/xml"}
  • produces:

    • 指定该方法能够生成的响应的 content-type(即服务器返回的数据类型)。spring 会根据请求的 accept header 和此属性进行内容协商(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/pathparamsheadersconsumesproduces 属性。

使用快捷方式注解的优点:

  • 更简洁: 代码更短。
  • 更清晰: 一眼就能看出方法处理的是哪种 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 方法,并提供最全面的配置选项(pathmethodparamsheadersconsumesproduces)。
  • @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的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com