码迷,mamicode.com
首页 > 编程语言 > 详细

使用spring ResponseEntity来处理HTTP的返回请求

时间:2019-05-14 00:57:59      阅读:830      评论:0      收藏:0      [点我收藏+]

标签:tags   process   xtend   produces   work   and   argument   cond   frame   

通常情况下,在前后端分离的大背景下,我们后台服务返回给前端的通常都是格式化的数据,比如Json,开始的时候,我们用json包生产一个json的字符串,配合http 协议的一些API 来自定义实现

            spring发展到现在,已经都包装出来了通用的处理类:ResponseEntity ,此类继承自HttpEntity
 public class ResponseEntity<T> extends HttpEntity<T> {
private final Object status;

/**
 * Create a new {@code ResponseEntity} with the given status code, and no body nor headers.
 * @param status the status code
 */
public ResponseEntity(HttpStatus status) {
    this(null, null, status);
}

/**
 * Create a new {@code ResponseEntity} with the given body and status code, and no headers.
 * @param body the entity body
 * @param status the status code
 */
public ResponseEntity(@Nullable T body, HttpStatus status) {
    this(body, null, status);
}
            并且做了扩展,用来处理http请求过程中的状态码 ,header,body 等数据。

ResponseEntity是一种泛型类型。因此,我们可以使用任何类型作为响应主体:

@Controller
public class XXXController{br/>@GetMapping("/hello")
public ResponseEntity<String> hello() {
return new ResponseEntity<>("Hello !", HttpStatus.OK);
}

这里字符串"Hello World!"作为字符串返回给REST端。

我们可以设置HTTP标头:

@GetMapping("/customHeader")
ResponseEntity<String> customHeader() {
HttpHeaders headers = new HttpHeaders();
headers.add("Custom-Header", "foo");

return new ResponseEntity<>(
"Custom header set", headers, HttpStatus.OK);
}

设置自定义标头:

@GetMapping("/customHeader")
ResponseEntity<String> customHeader() {
return ResponseEntity.ok()
.header("Custom-Header", "foo")
.body("Custom header set")

如果将一个对象放入:

@GetMapping("/hello")
public ResponseEntity<String> hello() {
return new ResponseEntity<>(new User(‘jdon’), HttpStatus.OK);
}

返回是JSON字符串:

[ { ‘name’: ‘jdon‘}]

下面是返回对象的JSON列表:

public ResponseEntity<List<ProcessDef>> repositoryProcessDefinitionsGet() {
return new ResponseEntity<>(processDefRepo.findAll(), HttpStatus.FOUND);
}

以上是通过ResponseEntity这个对象在代码中灵活操控响应,但是在一般情况下我们只是想返回一个带有数据的正常响应,那么只要使用@注解即可

@ResponseBody
在类级别使用@Controller标注情况下, @ResponseBody注解告诉返回的对象将自动序列化为JSON,并通过回控制器的HttpResponse对象。

@Controller
public class XXXController{

@ResponseBody
public User postResponseController(@RequestBody LoginForm loginForm) {
return new User("Thanks For Posting!!!");
}

将返回客户端JSON字符串:

[ { ‘name’: Thanks For Posting!!!"}]

在@RestController注解了类的情况下,我们就不需要再使用@ResponseBody了,可以直接返回对象,并使用ResponseStatus返回状态码!

@ResponseStatus
ResponseStatus虽然只是规定了返回的状态,但是只需要标注在方法上,简单,而且状态码与返回类型分离,比较清晰。我们将上面返回对象列表的代码使用ResponseStatus改写如下,注意类级别@RestController:

@RestController
public class XXXController{

@ResponseStatus(HttpStatus.FOUND)
public User postResponseController() {
return new User("Thanks For Posting!!!");
}

这也会返回客户端JSON字符串:

[ { ‘name’: Thanks For Posting!!!"}]

这样的代码更加专注于业务。

直接操控响应
Spring还允许我们直接访问javax.servlet.http.HttpServletResponse对象; 我们只需要将它声明为方法参数:

@GetMapping("/manual")
public void manual(HttpServletResponse response) throws IOException {
response.setHeader("Custom-Header", "foo");
response.setStatus(200);
response.getWriter().println("Hello World!");
}

由于Spring在底层实现之上提供了抽象和附加功能,因此如果以这种方式直接操纵响应,会失去很多Spring提供方便功能。

实例代码:

import io.swagger.annotations.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.constraints.*;

@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2019-03-09T21:32:18.308+08:00")

@Api(value = "tag", tags={ "tag", }, description = "the tag API")
public interface TagApi {

@ApiOperation(value = "获取问题概要标签列表", notes = "get_issue_summary_tags", response = OperateResult.class, tags={ "tag", })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK", response = OperateResult.class),
    @ApiResponse(code = 500, message = "system error", response = Void.class) })

@RequestMapping(value = "/tag/{issue_summary_key}/tags",
    produces = { "application/json" }, 
    method = RequestMethod.GET)
default ResponseEntity<OperateResult> getIssueSummaryTags(@NotNull @ApiParam(value = "项目key", required = true) @RequestParam(value = "project_key", required = true) String projectKey, @ApiParam(value = "issue_summary_key", required = true) @PathVariable("issue_summary_key") String issueSummaryKey) {
    // do some magic!
    return new ResponseEntity<OperateResult>(HttpStatus.OK);
}

@ApiOperation(value = "获取问题概要标签值列表", notes = "get_tag_values", response = OperateResult.class, tags={ "tag", })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK", response = OperateResult.class),
    @ApiResponse(code = 500, message = "system error", response = Void.class) })

@RequestMapping(value = "/tag/{issue_summary_key}/tag_value/{tag_type}",
    produces = { "application/json" }, 
    method = RequestMethod.GET)
default ResponseEntity<OperateResult> getTagValues(@NotNull @ApiParam(value = "项目key", required = true) @RequestParam(value = "project_key", required = true) String projectKey, @ApiParam(value = "issue_summary_key", required = true) @PathVariable("issue_summary_key") String issueSummaryKey, @ApiParam(value = "标签类型 app: 应用 device: 设备 server_name:服务名称 level:级别 logger:日志 os: 系统 user: 用户 url:URL transaction:事物", required = true) @PathVariable("tag_type") String tagType, @NotNull @Min(1) @ApiParam(value = "当前页数", required = true, defaultValue = "1") @RequestParam(value = "page_number", required = true, defaultValue = "1") Integer pageNumber, @NotNull @Min(1) @ApiParam(value = "每页显示条数", required = true, defaultValue = "10") @RequestParam(value = "page_size", required = true, defaultValue = "10") Integer pageSize) {
    // do some magic!
    return new ResponseEntity<OperateResult>(HttpStatus.OK);
}

}

@Controller
public class TagApiController implements TagApi {

private final static Logger logger = LoggerFactory.getLogger(TagApiController.class);

@Autowired
private TagService tagService;

@Override
public ResponseEntity<OperateResult> getIssueSummaryTags(@NotNull @ApiParam(value = "项目key", required = true) @RequestParam(value = "project_key", required = true) String projectKey, @ApiParam(value = "issue_summary_key", required = true) @PathVariable("issue_summary_key") String issueSummaryKey) {
    OperateResult operateResult = new OperateResult();
    try {
        Preconditions.checkArgument(StringUtils.isNotBlank(projectKey));
        Preconditions.checkArgument(StringUtils.isNotBlank(issueSummaryKey));
        List<TagDetail> tagValueArrayList = tagService.getIssueSummaryTagList(projectKey, issueSummaryKey);
        operateResult = OperateResult.success(tagValueArrayList);
        return new ResponseEntity<OperateResult>(operateResult,HttpStatus.OK);
    } catch (Exception e) {
        logger.error("api getIssueSummaryTags error.{}", e);
        operateResult = OperateResult.exception(OperateCode.SYSTEM_ERROR,e);
        return new ResponseEntity<OperateResult>(operateResult, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

使用spring ResponseEntity来处理HTTP的返回请求

标签:tags   process   xtend   produces   work   and   argument   cond   frame   

原文地址:https://blog.51cto.com/chenhva/2393868

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!