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)

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

相关推荐
uzong1 小时前
技术故障复盘模版
后端
GetcharZp1 小时前
基于 Dify + 通义千问的多模态大模型 搭建发票识别 Agent
后端·llm·agent
桦说编程2 小时前
Java 中如何创建不可变类型
java·后端·函数式编程
lifallen2 小时前
Java Stream sort算子实现:SortedOps
java·开发语言
IT毕设实战小研2 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
wyiyiyi2 小时前
【Web后端】Django、flask及其场景——以构建系统原型为例
前端·数据库·后端·python·django·flask
没有bug.的程序员3 小时前
JVM 总览与运行原理:深入Java虚拟机的核心引擎
java·jvm·python·虚拟机
甄超锋3 小时前
Java ArrayList的介绍及用法
java·windows·spring boot·python·spring·spring cloud·tomcat
阿华的代码王国3 小时前
【Android】RecyclerView复用CheckBox的异常状态
android·xml·java·前端·后端
Zyy~3 小时前
《设计模式》装饰模式
java·设计模式