springmvc @ResponseStatus和ResponseEntity的使用

 更新时间:2024年07月04日 15:51:02   作者:Saleson  
这篇文章主要介绍了springmvc @ResponseStatus和ResponseEntity的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

使用@ResponseStatus和ResponseEntity

@ResponseStatus

是标记一个方法或异常类在返回时响应的http状态。

其代码注释如下:

*
* <p>The status code is applied to the HTTP response when the handler
* method is invoked and overrides status information set by other means,
* like {@code ResponseEntity} or {@code "redirect:"}.
*
* <p><strong>Warning</strong>: when using this annotation on an exception
* class, or when setting the {@code reason} attribute of this annotation,
* the {@code HttpServletResponse.sendError} method will be used.
*
* <p>With {@code HttpServletResponse.sendError}, the response is considered
* complete and should not be written to any further. Furthermore, the Servlet
* container will typically write an HTML error page therefore making the
* use of a {@code reason} unsuitable for REST APIs. For such cases it is
* preferable to use a {@link org.springframework.http.ResponseEntity} as
* a return type and avoid the use of {@code @ResponseStatus} altogether.
*
* <p>Note that a controller class may also be annotated with
* {@code @ResponseStatus} and is then inherited by all {@code @RequestMapping}
* methods.

@ResponseStatus 可以结合 @ResponseBody 一起使用。

@RequestMapping("/testResponseBody")
@ResponseBody
public Map<String, String> testResponseBody(){
    return ImmutableMap.of("key", "value");
}


@RequestMapping("/testResponseBodyFaild")
@ResponseBody
@ResponseStatus(HttpStatus.NOT_IMPLEMENTED)
public Map<String, String> testResponseBodyFaild(){
    return ImmutableMap.of("key", "faild");
}

这两个handler method返回的http status code(http状态码) 分别是200 和 501。

ResponseEntity

是在 org.springframework.http.HttpEntity 的基础上添加了http status code(http状态码),用于RestTemplate以及@Controller的HandlerMethod。

它在Controoler中或者用于服务端响应时,作用是和@ResponseStatus与@ResponseBody结合起来的功能一样的。用于RestTemplate时,它是接收服务端返回的http status code 和 reason的。

代码注释如下:

 * Extension of {@link HttpEntity} that adds a {@link HttpStatus} status code.
 * Used in {@code RestTemplate} as well {@code @Controller} methods.
 *
 * <p>In {@code RestTemplate}, this class is returned by
 * {@link org.springframework.web.client.RestTemplate#getForEntity getForEntity()} and
 * {@link org.springframework.web.client.RestTemplate#exchange exchange()}:
 * <pre class="code">
 * ResponseEntity&lt;String&gt; entity = template.getForEntity("http://example.com", String.class);
 * String body = entity.getBody();
 * MediaType contentType = entity.getHeaders().getContentType();
 * HttpStatus statusCode = entity.getStatusCode();
 * </pre>
 *
 * <p>Can also be used in Spring MVC, as the return value from a @Controller method:
 * <pre class="code">
 * &#64;RequestMapping("/handle")
 * public ResponseEntity&lt;String&gt; handle() {
 *   URI location = ...;
 *   HttpHeaders responseHeaders = new HttpHeaders();
 *   responseHeaders.setLocation(location);
 *   responseHeaders.set("MyResponseHeader", "MyValue");
 *   return new ResponseEntity&lt;String&gt;("Hello World", responseHeaders, HttpStatus.CREATED);
 * }
 * </pre>
 * Or, by using a builder accessible via static methods:
 * <pre class="code">
 * &#64;RequestMapping("/handle")
 * public ResponseEntity&lt;String&gt; handle() {
 *   URI location = ...;
 *   return ResponseEntity.created(location).header("MyResponseHeader", "MyValue").body("Hello World");
 * }
 * </pre>

ResponseEntity 和 @ResponseStatus 一起使用是无效的

@RequestMapping("/testResponseEntity")
public ResponseEntity<Map<String, String>> testResponseEntity(){
    Map<String, String> map = ImmutableMap.of("key", "value");
    return ResponseEntity.ok(map);
}

@RequestMapping("/testResponseEntityFaild")
@ResponseStatus(HttpStatus.NOT_IMPLEMENTED)
public ResponseEntity<Map<String, String>> testResponseEntityFaild(){
    Map<String, String> map = ImmutableMap.of("key", "faild");
    return ResponseEntity.ok(map);
}


@RequestMapping("/testResponseEntityFaild2")
public ResponseEntity<Map<String, String>> testResponseEntityFaild2(){
    return ResponseEntity.badRequest().body(ImmutableMap.of("key", "faild"));
}

这三个handler method返回的http status code(http状态码) 分别是200 、 200 和 400。

完整的TestController代码

 import com.google.common.collect.ImmutableMap;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * Created by saleson on 2017/5/5.
 */
@RestController
@RequestMapping("/test")
public class TestController {

    @RequestMapping("/testResponseEntity")
    public ResponseEntity<Map<String, String>> testResponseEntity(){
        Map<String, String> map = ImmutableMap.of("key", "value");
        return ResponseEntity.ok(map);
    }

    @RequestMapping("/testResponseEntityFaild")
    @ResponseStatus(HttpStatus.NOT_IMPLEMENTED)
    public ResponseEntity<Map<String, String>> testResponseEntityFaild(){
        Map<String, String> map = ImmutableMap.of("key", "faild");
        return ResponseEntity.ok(map);
    }


    @RequestMapping("/testResponseEntityFaild2")
    public ResponseEntity<Map<String, String>> testResponseEntityFaild2(){
        return ResponseEntity.badRequest().body(ImmutableMap.of("key", "faild"));
    }


    @RequestMapping("/testResponseBody")
    @ResponseBody
    public Map<String, String> testResponseBody(){
        return ImmutableMap.of("key", "value");
    }

    @RequestMapping("/testResponseBodyFaild")
    @ResponseBody
    @ResponseStatus(HttpStatus.NOT_IMPLEMENTED)
    public Map<String, String> testResponseBodyFaild(){
        return ImmutableMap.of("key", "faild");
    }
}

返回的http status code截图:

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 通过实例解析spring bean之间的关系

    通过实例解析spring bean之间的关系

    这篇文章主要介绍了通过实例解析spring bean之间的关系,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-01-01
  • java操作文件之文件重命名实现方式

    java操作文件之文件重命名实现方式

    这篇文章主要介绍了java操作文件之文件重命名实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2026-03-03
  • RocketMq同组消费者如何自动设置InstanceName

    RocketMq同组消费者如何自动设置InstanceName

    这篇文章主要介绍了RocketMq同组消费者如何自动设置InstanceName问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-06-06
  • 基于JWT实现SSO单点登录流程图解

    基于JWT实现SSO单点登录流程图解

    这篇文章主要介绍了基于JWT实现SSO单点登录流程图解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-07-07
  • SpringBoot配置图片访问的虚拟路径

    SpringBoot配置图片访问的虚拟路径

    大家好,本篇文章主要讲的是SpringBoot配置图片访问的虚拟路径,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下
    2022-02-02
  • javaWeb使用servlet搭建服务器入门

    javaWeb使用servlet搭建服务器入门

    这篇文章主要为大家详细介绍了javaWeb使用servlet搭建服务器入门,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-11-11
  • @Bean注解和@Configuration、@Component注解组合使用的区别

    @Bean注解和@Configuration、@Component注解组合使用的区别

    这篇文章主要介绍了@Bean注解和@Configuration、@Component注解组合使用的区别,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11
  • java根据负载自动抓取jstack dump详情

    java根据负载自动抓取jstack dump详情

    这篇文章主要介绍了java根据负载自动抓取jstack dump详情,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-09-09
  • java并发访问重复请求过滤问题

    java并发访问重复请求过滤问题

    本篇文章给大家分享了关于java并发访问重复请求过滤的相关问题以及解决方法,对此有需要的朋友参考学习下。
    2018-05-05
  • Java的设计模式之代理模式使用详解

    Java的设计模式之代理模式使用详解

    这篇文章主要介绍了Java的设计模式之代理模式使用详解,代理模式是23种设计模式之一,它关心的主要是过程,而不是结果,代理模式主要提供了对目标对象的间接访问方式,即通过代理对象来访问目标对象,需要的朋友可以参考下
    2024-01-01

最新评论