189 8069 5689

使用springResponseEntity来处理HTTP的返回请求

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

十年的集美网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。全网营销推广的优势是能够根据用户设备显示端的尺寸不同,自动调整集美建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。成都创新互联公司从事“集美网站设计”,“集美网站推广”以来,每个客户项目都认真落实执行。

            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{@GetMapping("/hello")
br/>@GetMapping("/hello")
hello() {
return new ResponseEntity<>("Hello !", HttpStatus.OK);
}

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

我们可以设置HTTP标头:

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

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

设置自定义标头:

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

如果将一个对象放入:

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

返回是JSON字符串:

[ { ‘name’: 'jdon'}]

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

public ResponseEntity> 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 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(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 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(HttpStatus.OK);
}

}

@Controller
public class TagApiController implements TagApi {

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

@Autowired
private TagService tagService;

@Override
public ResponseEntity 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 tagValueArrayList = tagService.getIssueSummaryTagList(projectKey, issueSummaryKey);
        operateResult = OperateResult.success(tagValueArrayList);
        return new ResponseEntity(operateResult,HttpStatus.OK);
    } catch (Exception e) {
        logger.error("api getIssueSummaryTags error.{}", e);
        operateResult = OperateResult.exception(OperateCode.SYSTEM_ERROR,e);
        return new ResponseEntity(operateResult, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

网页标题:使用springResponseEntity来处理HTTP的返回请求
本文地址:http://cdxtjz.com/article/ighioo.html

其他资讯