%DATE% %TIME%

16:21 March 11, 2021

This handles the 500 errors that weren’t thrown

Define a filter and set the level to the highest

package com.fedtech.common.filter.response;

import com.fedtech.common.util.result.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/** * Process part of the response **@author <a href = "mailto:[email protected]" > huan </a >
 * @date 2021/2/24
 * @since1.0.0 * /
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ResponseFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}@Override
    public void destroy(a) {}@Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {

        ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) servletResponse);
        filterChain.doFilter(servletRequest, responseWrapper);
        String contentType = responseWrapper.getContentType();
        byte[] content = responseWrapper.getResponseData();
        String str = "";
        if (StringUtils.isNotBlank(contentType) && (contentType.contains(MediaType.APPLICATION_JSON_VALUE) || contentType.contains(MediaType.TEXT_HTML_VALUE))) {
            str = new String(content);
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            if(response.getStatus() ! =200) {
                if (StringUtils.containsAny(str, "\"status\":\"false\"")) {
                    writeResponse(response, response.getStatus(), str);
                } else{ writeResponse(response, response.getStatus(), R.failedWithJsonData(str).toJson()); }}else {
                if (StringUtils.containsAny(str, "\"status\":\"true\"")) {
                    writeResponse(response, response.getStatus(), str);
                } else{ writeResponse(response, response.getStatus(), R.successWithJsonData(str).toJson()); }}}}private static void writeResponse(HttpServletResponse response, int status, String json) {
        try {
            response.setHeader("Access-Control-Allow-Origin"."*");
            response.setHeader("Access-Control-Allow-Methods"."*");
            response.setContentType("application/json; charset=UTF-8");
            response.setStatus(status);
            response.getWriter().write(json);
        } catch(IOException e) { e.printStackTrace(); }}}Copy the code

Unified response processing

package com.fedtech.common.filter.response;

import com.fedtech.common.util.result.R;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.*;

public class ResponseWrapper extends HttpServletResponseWrapper {
    private ByteArrayOutputStream buffer = null;
    private ServletOutputStream out = null;
    private PrintWriter writer = null;

    ResponseWrapper(HttpServletResponse resp) throws IOException {
        super(resp);
        buffer = new ByteArrayOutputStream();// A real stream that stores data
        out = new WapperedOutputStream(buffer);
        writer = new PrintWriter(new OutputStreamWriter(buffer));
    }

    @Override
    public ServletOutputStream getOutputStream(a) throws IOException {
        return out;
    }

    @Override
    public PrintWriter getWriter(a) throws UnsupportedEncodingException {
        return writer;
    }

    @Override
    public void flushBuffer(a) throws IOException {
        if(out ! =null) {
            out.flush();
        }
        if(writer ! =null) { writer.flush(); }}@Override
    public void reset(a) {
        buffer.reset();
    }

    byte[] getResponseData() throws IOException {
        flushBuffer();
        if (StringUtils.contains(buffer.toString(), "\"data\":") && StringUtils.contains(buffer.toString(), "\"code\":")
                && StringUtils.contains(buffer.toString(), "\"status\":")) {
            return buffer.toByteArray();
        }
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        stream.write(R.successWithJsonData(buffer.toString()).toJson().getBytes());
        return stream.toByteArray();
    }

    public String getContent(a) throws IOException {
        flushBuffer();
        if (StringUtils.contains(buffer.toString(), "\"data\":") && StringUtils.contains(buffer.toString(), "\"code\":")
                && StringUtils.contains(buffer.toString(), "\"status\":")) {
            return buffer.toString();
        }
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        stream.write(R.successWithJsonData(buffer.toString()).toJson().getBytes());
        return stream.toString();
    }


    private class WapperedOutputStream extends ServletOutputStream {
        private ByteArrayOutputStream bos = null;

        WapperedOutputStream(ByteArrayOutputStream stream) throws IOException {
            bos = stream;
        }

        @Override
        public void write(int b) throws IOException {
            bos.write(b);
        }

        @Override
        public void write(byte[] b) throws IOException {
            bos.write(b, 0, b.length);
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            bos.write(b, off, len);
        }

        @Override
        public boolean isReady(a) {
            return false;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {}}}Copy the code

This article is published by OpenWrite, a blogging tool platform