Skip to content

Commit

Permalink
项目第一版本v_0.1.4 新增自动处理返回
Browse files Browse the repository at this point in the history
  • Loading branch information
15139467313 committed May 18, 2024
1 parent e7e3648 commit dce4bd3
Show file tree
Hide file tree
Showing 11 changed files with 329 additions and 32 deletions.
9 changes: 2 additions & 7 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

<groupId>io.github.15139467313</groupId>
<artifactId>czh-tool</artifactId>
<version>0.0.5</version>
<version>0.1.4</version>
<name>czh-tool</name>
<description>czh-tool</description>
<url>https://github.com/15139467313/czh-tool</url>
Expand Down Expand Up @@ -52,12 +52,7 @@
<dependencies>


<!-- https://mvnrepository.com/artifact/com.feiniaojin/graceful-response -->
<dependency>
<groupId>com.feiniaojin</groupId>
<artifactId>graceful-response</artifactId>
<version>3.2.0-boot2</version>
</dependency>



<!-- Spring Boot Starter,用于构建 Web 应用 -->
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package com.czh.tool.czh.tool.config;

/**
* @ClassNAME GlobalResponseHandler
* @Description TODO
* @Author czh
* @Date 2024/5/18 22:08
* @Version 1.0
*/

import com.czh.tool.czh.tool.response.AjaxResult;
import com.czh.tool.czh.tool.response.ResponseFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;
import java.util.Objects;

@ControllerAdvice
@Order(value = 1000)
public class GlobalResponseHandlerConfig implements ResponseBodyAdvice<Object> {




@Autowired
private ResponseFactory responseFactory;

@Autowired
private ObjectMapper objectMapper;

@Override
public boolean supports(MethodParameter methodParameter, Class clazz) {
return Objects.requireNonNull(methodParameter.getMethod()).getReturnType().equals(Void.TYPE);
}

@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

// 将响应体包装成 ApiResponse 对象
ValidatedSuccessConfig<Object> apiResponse = (ValidatedSuccessConfig<Object>) responseFactory.newSuccessInstance(body);

// 如果返回值是 String 类型,将 ApiResponse 对象转换为 JSON 字符串
if (body instanceof String) {
try {
return objectMapper.writeValueAsString(apiResponse);
} catch (Exception e) {
throw new RuntimeException("Error converting ApiResponse to JSON string", e);
}
}

// 否则返回 ApiResponse 对象
return apiResponse;

}
}

42 changes: 42 additions & 0 deletions src/main/java/com/czh/tool/czh/tool/config/ToolAutoConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package com.czh.tool.czh.tool.config;

import com.czh.tool.czh.tool.exception.CzhExceptionControllerAdvice;
import com.czh.tool.czh.tool.exception.GrNotVoidResponseBodyAdvice;
import com.czh.tool.czh.tool.response.ResponseFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ToolAutoConfig {

@Bean
public CzhExceptionControllerAdvice controllerAdvice() {
return new CzhExceptionControllerAdvice();
}

@Bean
public GlobalResponseHandlerConfig globalResponseHandler() {
return new GlobalResponseHandlerConfig();
}

@Bean
public ValidatedExceptionConfig validatedExceptionConfig() {
return new ValidatedExceptionConfig();
}

@Bean
public ValidatedSuccessConfig validatedSuccessConfig() {
return new ValidatedSuccessConfig();
}

@Bean
public ResponseFactory responseFactory() {
return new ResponseFactory();
}

@Bean
public GrNotVoidResponseBodyAdvice grNotVoidResponseBodyAdvice() {
return new GrNotVoidResponseBodyAdvice();
}

}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,19 @@
* @author czh
* @since 1.0
*/
@ConfigurationProperties(prefix = "czh.tool")
@ConfigurationProperties(prefix = "czh.tool.error")
@Component
public class ValidatedExceptionConfig implements Serializable {

/**
* 验证失败错误码
*/
private Integer code;
private Integer code=500;

/**
* 验证失败错误信息
*/
public String message;
public String message="参数校验失败";


public Integer getCode() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package com.czh.tool.czh.tool.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
*
* @author czh
* @since 1.0
*/
@ConfigurationProperties(prefix = "czh.tool.success")
@Component
public class ValidatedSuccessConfig<T> implements Serializable {

/**
* 成功返回码
*/
private Integer code=200;

/**
* 验证失败错误信息
*/
public String message="请求成功";

private T data;

public ValidatedSuccessConfig(Integer code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}

public ValidatedSuccessConfig() {
}

public Integer getCode() {
return code;
}

public void setCode(Integer code) {
this.code = code;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public T getData() {
return data;
}

public void setData(T data) {
this.data = data;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.czh.tool.czh.tool.response.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
Expand All @@ -24,6 +25,7 @@
*/
@Slf4j
@RestControllerAdvice()
@Order(value = 1000)
public class CzhExceptionControllerAdvice {

@Autowired
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package com.czh.tool.czh.tool.exception;


import com.czh.tool.czh.tool.config.ValidatedSuccessConfig;
import com.czh.tool.czh.tool.response.AjaxResult;
import com.czh.tool.czh.tool.response.ResponseFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
* 非空返回值的处理.
*
* @author <a href="mailto:[email protected]">Yujie</a>
* @version 0.1
* @since 0.1
*/
@ControllerAdvice
@Order(value = 1000)
public class GrNotVoidResponseBodyAdvice implements ResponseBodyAdvice<Object> {

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


@Autowired
private ResponseFactory responseFactory;

@Autowired
private ObjectMapper objectMapper;
/**
* 路径过滤器
*/
private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

/**
* 只处理不返回void的,并且MappingJackson2HttpMessageConverter支持的类型.
*
* @param methodParameter 方法参数
* @param clazz 处理器
* @return 是否支持
*/
@Override
public boolean supports(MethodParameter methodParameter,
Class<? extends HttpMessageConverter<?>> clazz) {
Method method = methodParameter.getMethod();

//method为空、返回值为void、非JSON,直接跳过
if (Objects.isNull(method)
|| method.getReturnType().equals(Void.TYPE)){
logger.debug("Graceful Response:method为空、返回值为void和Response类型、非JSON,跳过");
return false;


}
//method为空、返回值为void、非JSON,直接跳过
if (method.getReturnType().getName().equals("com.czh.tool.czh.tool.response.AjaxResult")){
return false;
}


return true;
}

@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

// 将响应体包装成 ApiResponse 对象
ValidatedSuccessConfig<Object> apiResponse = (ValidatedSuccessConfig<Object>) responseFactory.newSuccessInstance(body);

// 如果返回值是 String 类型,将 ApiResponse 对象转换为 JSON 字符串
if (body instanceof String) {
try {
return objectMapper.writeValueAsString(apiResponse);
} catch (Exception e) {
throw new RuntimeException("Error converting ApiResponse to JSON string", e);
}
}

// 否则返回 ApiResponse 对象
return apiResponse;


}


}
22 changes: 22 additions & 0 deletions src/main/java/com/czh/tool/czh/tool/response/EnableResponse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.czh.tool.czh.tool.response;

import com.czh.tool.czh.tool.config.ToolAutoConfig;
import org.springframework.context.annotation.Import;

import java.lang.annotation.*;


/**
* 注解启动全局结果处理的入口.
*
* @author czh
* @version 0.1
* @since 0.1
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(ToolAutoConfig.class)
public @interface EnableResponse {
}
Loading

0 comments on commit dce4bd3

Please sign in to comment.