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截图:

总结

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

相关文章

  • 关于@Value注入List,Map及设置默认值问题

    关于@Value注入List,Map及设置默认值问题

    这篇文章主要介绍了@Value注入List,Map及设置默认值问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-05-05
  • SpringCloud链路追踪组件Sleuth配置方法解析

    SpringCloud链路追踪组件Sleuth配置方法解析

    这篇文章主要介绍了SpringCloud链路追踪组件Sleuth配置方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-03-03
  • java的Stream流处理示例小结

    java的Stream流处理示例小结

    Stream API提供了一种高效、声明式的数据处理方式,是现代 Java 编程中不可或缺的工具,合理使用可以大幅提升代码的可读性和维护性,这篇文章主要介绍了java的Stream流处理,需要的朋友可以参考下
    2025-06-06
  • Java mybatis 开发自定义插件

    Java mybatis 开发自定义插件

    这篇文章主要介绍了Java mybatis开发自定义插件,MyBatis允许你在映射语句执行过程中的某一点进行拦截调用,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-08-08
  • 详解Java的四种引用方式及其区别

    详解Java的四种引用方式及其区别

    这篇文章主要介绍了Java的四种引用方式 ,主要主要包括强引用,软引用,弱引用,虚引用,稍微整理精简一下做下分享,具有一定的参考价值,需要的朋友可以参考下
    2018-12-12
  • Java中@JSONField和@JsonProperty注解的用法及区别详解

    Java中@JSONField和@JsonProperty注解的用法及区别详解

    @JsonProperty和@JSONField注解都是为了解决obj转json字符串的时候,将java bean的属性名替换成目标属性名,下面这篇文章主要给大家介绍了关于Java中@JSONField和@JsonProperty注解的用法及区别的相关资料,需要的朋友可以参考下
    2024-06-06
  • Java抽象类和普通类区别、 数组跟List的区别解析

    Java抽象类和普通类区别、 数组跟List的区别解析

    这篇文章主要介绍了Java抽象类和普通类区别、 数组跟List的区别,在这里需要注意List是一个接口,不能直接实例化,需要使用具体的实现类来创建对象,本文结合示例代码介绍的非常详细,需要的朋友参考下吧
    2023-09-09
  • 4位吸血鬼数字的java实现思路与实例讲解

    4位吸血鬼数字的java实现思路与实例讲解

    今天小编就为大家分享一篇关于4位吸血鬼数字的java实现思路与实例讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-03-03
  • JDBC实现Mysql自动重连机制的方法详解

    JDBC实现Mysql自动重连机制的方法详解

    最近在工作中发现了一个问题,通过查找相关的资料终于解决了,下面这篇文章主要给大家介绍了关于JDBC实现Mysql自动重连机制的相关资料,文中给出多种解决的方法,需要的朋友可以参考借鉴,下面来一起看看吧。
    2017-07-07
  • Java的JDBC编程使用之连接Mysql数据库

    Java的JDBC编程使用之连接Mysql数据库

    这篇文章主要给大家介绍了关于Java的JDBC编程使用之连接Mysql数据库的相关资料,JDBC是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,需要的朋友可以参考下
    2023-12-12

最新评论