我在我的网关(GateWay)中尝试添加一个自定义的过滤器,用来检测用户是否携带Token,如果未携带Token那么就返回我自己定义的统一返回类,但是在此过程中,我却发现,当我向其返回中文提示信息时,其中文被返回为乱码,如下。
公共返回类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CommonResult<T> {
public Integer code;
public String msg;
public T data;
public static CommonResult success(){
CommonResult commonResult = new CommonResult<>();
commonResult.setCode(ResponseCode.SUCCESS.getCode());
commonResult.setMsg(ResponseCode.SUCCESS.getMsg());
return commonResult;
}
public static <T>CommonResult<T> success(T data){
CommonResult commonResult = new CommonResult<>();
commonResult.setCode(ResponseCode.SUCCESS.getCode());
commonResult.setMsg(ResponseCode.SUCCESS.getMsg());
commonResult.setData(data);
return commonResult;
}
public static CommonResult fail(){
CommonResult commonResult = new CommonResult<>();
commonResult.setCode(ResponseCode.FAIL.getCode());
commonResult.setMsg(ResponseCode.FAIL.getMsg());
return commonResult;
}
public static <T>CommonResult<T> fail(T data){
CommonResult commonResult = new CommonResult<>();
commonResult.setCode(ResponseCode.FAIL.getCode());
commonResult.setMsg(ResponseCode.FAIL.getMsg());
commonResult.setData(data);
return commonResult;
}
}
GateWay全局过滤器
@Component
public class TokenFilter implements GlobalFilter{
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain){
ServerHttpResponse response = exchange.getResponse();
List<String> token = exchange.getRequest().getHeaders().get("token");
if (Objects.isNull(token)){
HashMap<String, Object> data = new HashMap<>();
data.put("tip","未登录");
try {
return response
.writeWith(Flux.just(exchange.getResponse().bufferFactory()
.wrap(new ObjectMapper().writeValueAsString(CommonResult.fail(data)).getBytes(StandardCharsets.UTF_8))));
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
return chain.filter(exchange);
}
}
经过一系列的检查,我发现向前台返回时需要进行设置UTF-8编码,可能在别的地方你会看到这样的例子。
response.setContentType("application/json;charset=utf-8");
当时你会发现在这里这种方式是行不通的,因为这里就没有这种方法,故你需要换一种方法进行添加。
response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
所以对全局过滤器进行修改。
@Component
public class TokenFilter implements GlobalFilter{
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain){
ServerHttpResponse response = exchange.getResponse();
// 添加此代码
response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
List<String> token = exchange.getRequest().getHeaders().get("token");
if (Objects.isNull(token)){
HashMap<String, Object> data = new HashMap<>();
data.put("tip","未登录");
try {
return response
.writeWith(Flux.just(exchange.getResponse().bufferFactory()
.wrap(new ObjectMapper().writeValueAsString(CommonResult.fail(data)).getBytes(StandardCharsets.UTF_8))));
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
return chain.filter(exchange);
}
}
修改后运行
至此,该问题解决