为什么 @HeadMapping 在 Spring MVC 中不可用?

okw*_*wap 7 java spring spring-mvc spring-boot

Spring 框架中包含以下注解。@GetMapping、@PostMapping、@PutMapping、@DeleteMapping 和 @PatchMapping,用于标准 Spring MVC 控制器方法,但 @HeadMapping 不是。这有什么意义?

Jac*_*gen 8

你总是可以回到@RequestMapping. 该注解支持所有类型的 HTTP 方法。@RequestMapping(method = { RequestMethod.HEAD })工作也是如此!


如果你确实想使用@HeadMapping,你可以自己创建:

@target({ ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = { RequestMethod.HEAD})
public @interface HeadMapping {
    @AliasFor(annotation = RequestMapping.class)
    String name() default "";

    @AliasFor(annotation = RequestMapping.class)
    String[] value() default {};

    @AliasFor(annotation = RequestMapping.class)
    String[] path() default {};

    @AliasFor(annotation = RequestMapping.class)
    String[] params() default {};

    @AliasFor(annotation = RequestMapping.class)
    String[] headers() default {};

    @AliasFor(annotation = RequestMapping.class)
    String[] consumes() default {};

    @AliasFor(annotation = RequestMapping.class)
    String[] produces() default {};
}
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案 (2认同)

sha*_*zin 5

根据HEAD 请求的W3 标准

9.4 HEAD

The HEAD method is identical to GET except that the server MUST NOT return a 
message-body in the response. The metainformation contained in the HTTP 
headers in response to a HEAD request SHOULD be identical to the information 
sent in response to a GET request. This method can be used for obtaining 
metainformation about the entity implied by the request without transferring 
the entity-body itself. This method is often used for testing hypertext 
links for validity, accessibility, and recent modification.
Run Code Online (Sandbox Code Playgroud)

它是一种类似于GET但不应该返回 Body 的请求方法。因此,您的GET方法也将有效地处理该HEAD方法,但不返回响应正文。

因此,理想情况下,您可以使用它@GetMapping来处理HEAD请求方法,并且可以避免Filter将响应返回给调用客户端,如本文所述

  • @AvPinzur 一般来说,这不是真的。这取决于您的数据源。例如,如果您从 MongoDB GridFS 下载文件,您可以读取长度和所有其他元数据,而无需读取文件。 (2认同)