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

发布于:2025-05-16 ⋅ 阅读:(10) ⋅ 点赞:(0)

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

@RestController
@RequestMapping("/user")   //第一层路径
public class UserController {

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

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

结果:

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

@RestController
public class UserController {

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

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

@RequestMapping("user")
public class UserController {

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

1.3 也可以写多层路径

@RestController
@RequestMapping("/user")
public class UserController {

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

 

2. 限制特定的方法访问

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

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

@RequestMapping添加method属性

@RestController
@RequestMapping("/user")
public class UserController {

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

或者使用

@GetMapping

@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)
 

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