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

问题描述 投票:0回答:2

Spring 框架中包含以下注释:

@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
适用于标准 Spring MVC 控制器方法。然而
@HeadMapping
不是。这有什么意义?

java spring spring-mvc spring-boot
2个回答
8
投票

你总是可以回到

@RequestMapping
。该注解支持所有类型的 HTTP 方法。所以
@RequestMapping(method = { RequestMethod.HEAD })
确实可以完成这项工作!


如果你真的想用

@HeadMapping
,你可以自己创建:

import org.springframework.core.annotation.AliasFor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.lang.annotation.*;

@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 {};
}

5
投票

根据 W3 标准 HEAD 请求

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.

它是一个类似于

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

因此,理想情况下,您可以使用

@GetMapping
来处理
HEAD
请求方法,并且可以使用
Filter
来避免将响应返回给调用客户端,如本 post

中所述
© www.soinside.com 2019 - 2024. All rights reserved.