繁体   English   中英

如何在 spring 引导中重用自定义响应

[英]How to reuse customized response in spring boot

我通过 spring 引导写了一个简单的 api。
当保存成功时,它会响应我用 json 类型制作的 200 个 httpStatus 代码。
但我想在全球范围内使用这个响应来重用它。

@PostMapping("/notice")
public ResponseEntity<Object> createNotice(@RequestBody @Valid NoticeDto noticeDto, HttpServletResponse response) {
    noticeService.createNotice(noticeDto);


    ObjectNode jsonResponse = null;
    try {
        ObjectMapper mapper = new ObjectMapper();

        jsonResponse = mapper.createObjectNode();
        jsonResponse.put("code", 200);
        jsonResponse.put("success", true);
        jsonResponse.put("msg", "OK");
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    PrintWriter out = response.getWriter();
    response.setStatus(200);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    out.flush();

}

例如,我想这样使用它。

@PostMapping("/notice")
public ResponseEntity<Object> createNotice(@RequestBody @Valid NoticeDto noticeDto, HttpServletResponse response) {
    noticeService.createNotice(noticeDto);
    
    return successResponse something...
}

为此,我应该写哪个 class 文件?
感谢您阅读我的问题。

您可以这样更改 controller 方法:

您可以通过多种方式实现这一目标。 其中一种方法如下所述。

package com.example.demo.controller;

import com.example.demo.dto.NoticeDto;
import com.example.demo.service.NoticeService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class DemoController {

    @Autowired(required = false)
    private NoticeService noticeService;

    @PostMapping(value = "/notice", produces = "application/json", 
   consumes="application/json")
public ResponseEntity<Map> createNotice(@RequestBody NoticeDto noticeDto) { //
    noticeService.createNotice(noticeDto);

    ObjectNode jsonResponse = null;
    try {
        ObjectMapper mapper = new ObjectMapper();

        jsonResponse = mapper.createObjectNode();
        jsonResponse.put("code", 200);
        jsonResponse.put("success", true);
        jsonResponse.put("msg", "OK");
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return new SuccessResponseWrapper<String>(jsonResponse.toPrettyString()).build();

}

}

您可以添加一个名为 SuccessResponseWrapper 的新 class。

package com.example.demo.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;

public class SuccessResponseWrapper<T> {

private ResponseEntity<T> responseEntity;

public SuccessResponseWrapper(T body) {
    HttpStatus status = HttpStatus.OK;
    responseEntity = new ResponseEntity<>(body, status);
}

public SuccessResponseWrapper(MultiValueMap<String, String> headers) {
    HttpStatus status = HttpStatus.OK;
    responseEntity = new ResponseEntity<>(headers, status);
}

public SuccessResponseWrapper(T body, MultiValueMap<String, String> headers) {
    HttpStatus status = HttpStatus.OK;
    responseEntity = new ResponseEntity<>(body, headers, status);
}

public SuccessResponseWrapper(T body, MultiValueMap<String, String> headers, int rawStatus) {
    responseEntity = new ResponseEntity<>(body, headers, 200);
}

    public ResponseEntity build() {
         return this.responseEntity;
    }
}

这样,您可以重用带有 Predefined http 响应代码 200 的 SuccessResponseWrapper。

你可以做这样的事情

class HttpResponsePrinter{
  public static  void ok(HttpServletResponse response){
      write(response, 200, 200, true, "OK");
  }
  private static void write(HttpServletResponse response,int httpCode, int code, bool success, String message) {
    ObjectNode jsonResponse = null;
    try {
        // you can reuse object mapper as well
        ObjectMapper mapper = new ObjectMapper();
        jsonResponse = mapper.createObjectNode();
        jsonResponse.put("code", code);
        jsonResponse.put("success", success);
        jsonResponse.put("msg", message);
      } catch (Exception ex) {
        ex.printStackTrace();
     }
     PrintWriter out = response.getWriter();
     response.setStatus(httpCode);
     response.setContentType("application/json");
     response.setCharacterEncoding("UTF-8");
     out.flush();
  }
}

用法:

@PostMapping("/notice")
public ResponseEntity<Object> createNotice(@RequestBody @Valid NoticeDto noticeDto, HttpServletResponse response) {
    noticeService.createNotice(noticeDto);
    HttpResponsePrinter.ok(response);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM