Spring MVC 接口的访问方法如何设置

@RequestMapping 是 Spring 框架中用于映射 HTTP 请求到控制器方法的注解。它支持以下 HTTP 方法访问类型,通过 method 属性指定:

  1. GET:用于获取资源
  2. POST:用于提交数据
  3. PUT:用于更新资源
  4. DELETE:用于删除资源
  5. PATCH:用于部分更新资源
  6. HEAD:类似于 GET 请求,但只返回状态行和头信息
  7. OPTIONS:返回服务器支持的 HTTP 方法
    现实情况GET方法和POST方法的使用占很大的部分,主要讲解GET和POST方法的使用,其他方法举一反三就可以了

1.所有方法都可以访问情况

@RequestMapping可以是类注解也可以是方法注解,加在类上或者加在方法上都可以,一般来说都建议在类上面加上,因为方便我们快速的定位问题。

java 复制代码
@RestController
@RequestMapping("/user")   //第一层路径
public class UserController {

    @RequestMapping("/u1") //第二层路径
    public String u1() {
        return "hello u1";
    }
}

将程序运行起来后,通过浏览器输入 http://localhost:8080/user/u1 访问,当然端口有可能不是8080,在运行的时候看一下就可以了

结果:

1.1 类注解可以不写,但是一般建议写上

java 复制代码
@RestController
public class UserController {

    @RequestMapping("/u1")
    public String u1() {
        return "hello u1";
    }
}

1.2 在写路径的时候不写 "/" 也可以,但是最好加上,这算是行业内的规范

java 复制代码
@RequestMapping("user")
public class UserController {

    @RequestMapping("u1")
    public String u1() {
        return "hello u1";
    }
}

1.3 也可以写多层路径

java 复制代码
@RestController
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/u/u1")
    public String u1() {
        return "hello u1";
    }
}

2. 限制特定的方法访问

这里我只举例get的访问方式,之后的简单介绍一下就ok了

在注解中添加method属性,可以通过这些属性设置访问的限定方式:

@RequestMapping添加method属性

java 复制代码
@RestController
@RequestMapping("/user")
public class UserController {

    @RequestMapping(value = "/u1", method = RequestMethod.GET)
    public String u1() {
        return "hello u1";
    }
}

或者使用

@GetMapping

java 复制代码
@RestController
@RequestMapping("/user")
public class UserController {

//    @RequestMapping(value = "/u1", method = RequestMethod.GET)
    @GetMapping("/u1")//就只能被get方法访问
    public String u1() {
        return "hello u1";
    }
}

不同方法测试

这里我们用postman来测试,不同的方法是否可以访问:

测试get方法:

测试post方法:

3.其他方法

快捷注解

为简化开发,Spring 还提供了针对特定 HTTP 方法的快捷注解:

  • @GetMapping:等同于 @RequestMapping(method = RequestMethod.GET)
  • @PostMapping:等同于 @RequestMapping(method = RequestMethod.POST)
  • @PutMapping:等同于 @RequestMapping(method = RequestMethod.PUT)
  • @DeleteMapping:等同于 @RequestMapping(method = RequestMethod.DELETE)
  • @PatchMapping:等同于 @RequestMapping(method = RequestMethod.PATCH)

这些快捷注解使代码更简洁易读,推荐优先使用。

相关推荐
Huyuejia2 分钟前
runtime-ask
后端
Rust研习社2 分钟前
90% 的 Rust 新手都不知道的 3 个实用开发技巧
后端·rust·编程语言
大圣编程6 分钟前
面向对象深度理解
java·开发语言·算法
影寂ldy13 分钟前
C# const 常量 / readonly 只读 / static readonly
java·开发语言·c#
摇滚侠17 分钟前
Maven 入门+高深 体系外 jar 包导入 172
java·maven·jar
做个文艺程序员26 分钟前
第02篇:K8s 存储与配置管理:ConfigMap、Secret、PV/PVC 实战——Java SaaS 多租户配置最佳实践
java·容器·kubernetes
爱吃牛肉的大老虎29 分钟前
Spring中用到的设计模式
java·spring·设计模式
Refrain_zc32 分钟前
Android TV 语音消息实战:遥控器 PCM 录音失真修复与扬声器强制播放方案
java
ZengLiangYi32 分钟前
sql.js WASM 深度解析
javascript·数据库·后端
Stick_ZYZ33 分钟前
从“能调用工具”到“能稳定执行任务”:Agent 工程化的下一步
java·人工智能·后端·spring·ai