【问题标题】:Why is @HeadMapping unavailable in Spring MVC?为什么 @HeadMapping 在 Spring MVC 中不可用?
【发布时间】:2017-12-17 20:17:54
【问题描述】:

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

【问题讨论】:

    标签: java spring spring-mvc spring-boot


    【解决方案1】:

    根据W3 Standard的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 的请求方法,但不应返回正文。因此,您的 GET 方法也将有效地处理 HEAD 方法,但不返回响应正文。

    因此,理想情况下,您可以使用@GetMapping 来处理HEAD 请求方法,并且可以使用Filter 来避免将响应返回给调用客户端,正如post 中所讨论的那样

    【讨论】:

    • 参考文章的简短回答:HEAD 响应应该包含准确的 Content-Length 标头,因此构建 GET 响应主体的工作可能无法避免。 (然后本文继续提供一些有用的实施建议。)
    • @AvPinzur 一般情况下并非如此。这取决于您的数据源。例如,如果您从 MongoDB GridFS 下载文件,则无需读取文件即可读取长度和所有其他元数据。
    【解决方案2】:

    您总是可以退回到@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 {};
    }
    

    【讨论】:

    • 这应该是公认的答案
    猜你喜欢
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-19
    • 1970-01-01
    相关资源
    最近更新 更多