【SpringBoot注解-5】web项目相关注解

时间:2022-07-25
本文章向大家介绍【SpringBoot注解-5】web项目相关注解,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

web项目常用注解 本文将对前文出现的一系列MVC注解,包括 @RestController、 @RequestMapping、@PathVariable、@RequestParam 以及 @RequestBody,进行更详细地解析与总结。

@RestController

@RestController 是MVC中应用非常频繁的一个注解,也是 SpringBoot 新增的一个注解,包括:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
    String value() default "";
}

@RestController作用是,返回JSON格式的数据,可以看作是 @Controller 和 @ResponseBody 的结合体。

@RequestMapping

@RequestMapping 是一个用来处理请求地址映射的注解,它可以用于类上,也可以用于方法上。用于类上的注解会将一个特定请求或者请求模式映射到一个控制器之上,表示类中的所有响应请求的方法都是以该地址作为父路径;方法的级别上注解表示进一步指定到处理方法的映射关系。 该注解有 6 个属性,一般在项目中比较常用的有 3 个属性:value、method 和 produces。

  1. value 属性:指定请求的实际地址,value 可以省略不写。
  2. method 属性:指定请求的类型,主要有GET、PUT、POST、DELETE,默认为 GET。
  3. produces 属性:指定返回内容类型。

@RequestMapping 使用示例:

@RestController
@RequestMapping(value = "/test", produces = "application/json; charset=UTF-8")
public class TestController {

    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public String testGet() {
        return "SUCCESS";
    }
}

启动项目在浏览器中输入:localhost:8080/test/get 即可。(8080由配置文件配置)。

为了简化使用,四种请求方法都有相应的注解,无需在 @RequestMapping 注解中加 method 属性来指定,上面的 GET方式请求可以直接使用 @GetMapping("/get") 注解,效果一样。相应地,PUT 方式、POST 方式和 DELETE方式对应的注解分别为 @PutMapping、@PostMapping 和 DeleteMapping。

@PathVariable

@PathVariable 注解主要用来获取 URL 参数,Spring Boot 支持 Restfull 风格的 URL,比如一个 GET 请求携带一个参数 id,我们将 id 作为参数接收,可以使用 @PathVariable 注解。如下:

@GetMapping("/student/{id}")
public String testPathVariable(@PathVariable Integer id) {
    System.out.println("获取到的id为:" + id);
    return "success";
}

对于URL,占位符可以在任何位置,不一定非要在最后,比如这样:/xxx/{id}/student。此外,URL 还支持多占位符,方法参数使用同样数量的参数来接收,例如:

@GetMapping("/student/{idd}/{name}")
public String testPathVariable(@PathVariable(value = "idd") Integer id, @PathVariable String name) {
    System.out.println("获取到的id为:" + id);
    System.out.println("获取到的name为:" + name);
    return "success";
}

运行项目,在浏览器中请求:localhost:8080/test/student/2/xiaohong, 可以看到控制台输出如下信息:

获取到的id为:2
获取到的name为:xiaohong

所以它支持多个参数的接收。同样地,如果 URL 中的参数和方法中的参数名称不同的话,也需要使用 value 属性来绑定两个参数。

@RequestParam

@RequestParam 也是获取请求参数的,@RequestParam 和 @PathVariable 有什么不同呢? 主要区别在于: @PathValiable 是从 URL 模板中获取参数值: http://localhost:8080/student/{id}; 而 @RequestParam 是从 Request 里获取参数值: http://localhost:8080/student?id=1。 我们使用该 URL 带上参数 id 来测试下如下代码:

@GetMapping("/student")
public String testRequestParam(@RequestParam Integer id) {
    System.out.println("前端传入的id为:" + id);
    return "success";
}

可以正常从控制台打印出 id 信息。同样地,URL 上面的参数和方法的参数需要一致,如果不一致,也需要使用 value 属性来说明,比如 URL 为:http://localhost:8080/student?idd=1。

@RequestMapping("/user")
public String testRequestParam(@RequestParam(value = "idd", required = false) Integer id) {
    System.out.println("前端传入的id为:" + id);
    return "success";
}

除了 value 属性外,还有两个属性比较常用。

  1. required 属性:true 表示该参数必传,否则就会报 404 错误,false 表示传不传皆可。
  2. defaultValue属性:默认值,表示请求中没有同名参数时的默认值。

从 URL 中可以看出,@RequestParam 注解用于 GET 请求上时,接收拼接在 URL 中的参数。除此之外,该注解还可以用于 POST 请求,接收前端表单提交的参数,假如前端通过表单提交 username 和 password 两个参数,那我们可以使用 @RequestParam 来接收,用法和上面一样。

@PostMapping("/form")
public String testForm(@RequestParam String username, @RequestParam String password) {
    System.out.println("前端传入的username为:" + username);
    System.out.println("前端传入的password为:" + password);
    return "SUCCESS";
}

我们使用 Postman 来模拟一下表单提交,测试一下接口:

如果表单数据很多,我们不可能在后台方法中写上很多参数,每个参数还要 @RequestParam 注解。针对这种情况,我们需要封装一个实体类来接收这些参数,实体中的属性名和表单中的参数名一致即可。

public class Student{
    private String username;
    private String password;
    // set get
}

使用实体接收的话,我们不必在前面加 @RequestParam 注解,直接使用即可。

@PostMapping("/form2")
public String testForm(Student student) {
    System.out.println("前端传入的username为:" + username);
    System.out.println("前端传入的password为:" + password);
    return "SUCCESS";
}

实际项目中,表单数据一般都有很多,这时需要封装一个实体类来接收表单数据。

@RequestBody

@RequestBody 注解用于接收前端传来的实体,接收参数也是对应的实体,比如前端通过 JSON 提交传来两个参数 username 和 password,此时我们需要在后端封装一个实体来接收。在传递的参数比较多的情况下,使用 @RequestBody 接收会非常方便。例如:

public class Student {
    private String username;
    private String password;
    // set get
}
@PostMapping("/user")
public String testRequestBody(@RequestBody Student student) {
    System.out.println("前端传入的username为:" + username);
    System.out.println("前端传入的password为:" + password);
    return "SUCCESS";
}

我们使用 Postman 工具来测试一下效果,打开 Postman,输入请求地址和参数,参数我们用 JSON 来模拟,如下图所有,调用之后返回 success。

同时看一下后台控制台输出的日志:

获取到的username为:xiaohong
获取到的password为:12345678

可以看出,@RequestBody 注解用于 POST 请求上,接收 JSON 实体参数。它和上面我们介绍的表单提交有点类似,只不过参数的格式不同,一个是 JSON 实体,一个是表单提交。在实际项目中根据具体场景和需要使用对应的注解即可。