spring mvc @ResponseStatus和ResponseEntity

转载 2018年04月17日 14:11:05

@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方法返回的http状态码(http状态码)分别是200和501。

ResponseEntity是在org.springframework.http.HttpEntity的基础上添加了http状态码(http状态码),用于RestTemplate以及@Controller的HandlerMethod。它在控制器中或用于服务端响应时,作用是和@ResponseStatus与@ResponseBody结合起来的功能一样的。用于RestTemplate时,它是接收服务端返回的http状态码和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"));
}

这三个处理程序方法返回的http状态码(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状态代码截图:

这里写图片描述

ResponseUtil的使用详情

1、Post请求

一般情况下,在非必须的情况下,使用Jquery实现post请求,而后台返回一般都需要手动封装ResponseUtil,和使用@ResponseBody注解来实现返回。



2、实例


1)前台代码:

[html] view plain copy
  1. <script type="text/javascript" src="JQuery/jquery-3.2.1.js"></script>  
[javascript] view plain copy
  1. function responseEntity(){  
  2.     $.post("${pageContext.request.contextPath}/Test/responseEntity.do",{},function(data){  
  3.         alert(data.message);  
  4.     });  
  5. }  
[html] view plain copy
  1. <input id="responseEntityTest" type="button" value="request" onclick="responseEntity()">  


2)后台代码:

[java] view plain copy
  1. @RequestMapping("/responseEntity.do")  
  2. public ResponseEntity<Map<String,Object>> responseEntity(){  
  3.     Map<String,Object> map = new HashMap<String,Object>();  
  4.     map.put("message""Hello Wrold");  
  5.     return new ResponseEntity<Map<String,Object>>(map, HttpStatus.OK);  
  6. }  
返回实体中,第一个参数为返回的数据,相当于out.write(map.toString()),第二个参数是状态码,可以设置返回404,上述设置等价于返回200.


3、结果




spring mvc @ResponseStatus 和 ResponseEntity

@ResponseStatus 是标记一个方法或异常类在返回时响应的http状态。其代码注释如下:* * The status code is applied to the HTTP response...
  • Mr_rain
  • Mr_rain
  • 2017-05-05 17:36:02
  • 9094

springmvc学习笔记(30)——ResponseStatus注解处理异常

ResponseStatusResponseStatus注解的使用非常简单,我们创建一个异常类,加上注解package com.zj.exception;import org.springframew...
  • u010837612
  • u010837612
  • 2015-04-30 11:25:40
  • 11428

SPRING MVC3.2案例讲解--SPRING MVC3的@ResponseBody和ResponseEntity

在传统的开发过程中,我们的控制CONTROLL层通常需要转向一个JSP视图;但随着WEB2.0相关技术的崛起,我们很多时候只需要返回数据即可,而不是一个JSP页面。 SPRING MVC3的@Resp...
  • json20080301
  • json20080301
  • 2013-10-11 17:15:20
  • 35690

@ResponseStatus注解的使用

带有@ResponseStatus注解的异常类会被ResponseStatusExceptionResolver 解析。可以实现自定义的一些异常,同时在页面上进行显示。具体的使用方法如下: ...
  • yalishadaa
  • yalishadaa
  • 2017-05-09 17:12:56
  • 3275

SpringMVC @ResponseStatus 的用法

@ResponseStatus 用于修饰一个类或者一个方法,修饰一个类的时候,一般修饰的是一个异常类,如下, 声明一个异常类在类上面加上ResponseStatus注解,就表明,在系统运行期间...
  • pengshuangbao520
  • pengshuangbao520
  • 2017-01-11 22:15:32
  • 3494

SpringMVC重要注解(一)@ExceptionHandler和@ResponseStatus

无论是普通的WEB项目,还是用SpringMVC实现的restful服务,都曾经历过下面两个问题: @PostMapping(path = "/selectByAcctcode") publi...
  • dreamsunday
  • dreamsunday
  • 2017-06-13 17:28:50
  • 1027

spring mvc @ResponseStatus 注解 注释返回中文乱码的问题

前言      前文中讲到,使用@ResponseStatus注解,可以修饰一个异常类,在发生异常的时候返回指定的错误码和消息,在返回的 reason中包含中文的时候,就会出现中文乱码的问题 现象...
  • pengshuangbao520
  • pengshuangbao520
  • 2017-01-13 20:44:49
  • 1472

springmvc ResponseEntity 下载文件损坏问题解决方法

这两天做一个文件下载功能,基本上使用的就是springmvc的ResponseEntity来做的,这块代码就不贴了,网上大把大把的,问题是下载的文件总是提示【文件损坏】导致打不开,word,excel...
  • u013555226
  • u013555226
  • 2017-08-10 09:26:59
  • 1846

使用springmvc中ResponseEntity下载文件

今天遇见了一个点击table列表中文件名,实现下载文件的功能。 因为这边的项目用的springmvc做的容器,以下是通过ajax访问该url通过输入流将数据(该数据通过url携带)中携带的文件内容(...
  • dd_king
  • dd_king
  • 2017-12-19 18:54:56
  • 490

SpringMVC使用ResponseEntity实现文件下载

上一篇写了文件上传,文件下载的配置过程同文件上传,有需要的请http://blog.csdn.net/c______________/article/details/77512017 本文主要通过R...
  • c______________
  • c______________
  • 2017-08-24 19:10:00
  • 2471
收藏助手
不良信息举报
您举报文章:spring mvc @ResponseStatus和ResponseEntity
举报原因:
原因补充:

(最多只允许输入30个字)