springboot使用ResponseBodyAdvice接口和@ControllerAdvice对返回结果进行处理

在权限控制的项目中碰到了列权限的控制,用户没有某个列权限时,返回时此列中的数据替换为***,用此方法可统一控制

pom.xml文件

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.test
mytest
0.0.1-SNAPSHOT


org.springframework.boot
spring-boot-starter-parent
2.0.3.RELEASE





org.springframework.boot
spring-boot-starter-web







org.springframework.boot
spring-boot-maven-plugin




实体类

package com.practice.entity;
public class MyEntity {
private Long id;
private String name;
private String sex;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "MyEntity [id=" + id + ", name=" + name + ", sex=" + sex + "]";
}

}


controller类

package com.practice.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.practice.entity.MyEntity;

@RestController
@RequestMapping("/api/test")
public class MyController {

@GetMapping("/get")
public List get() {
return getList();
}
private static List getList() {
// 模拟从数据库获取返回的数据
List list = new ArrayList();
for (int i = 0; i < 5; i++) {
MyEntity e = new MyEntity();
e.setId((long) i);
e.setName("name" + i);
e.setSex("男");
list.add(e);
}
return list;
}

}


对返回前的数据进行处理

package com.practice.config;
import java.util.List;
import org.springframework.core.MethodParameter;
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.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice(annotations = RestController.class)//此处只对有@RestController注解的类进行处理
public class MyResponseBodyAdvice implements ResponseBodyAdvice> {
@Override
public boolean supports(MethodParameter returnType, Class> converterType) {
// 根据业务和上面各个参数判断,是否执行下面的beforeBodyWrite方法,返回true则执行,否则不执行
return true;
}


@Override
public List beforeBodyWrite(List body, MethodParameter returnType, MediaType selectedContentType,
Class> selectedConverterType, ServerHttpRequest request,
ServerHttpResponse response) {
// 此处的body即为返回前的返回结果,可对此进行处理,如加密,替换等等,如数据列权限的控制,可在此处用反射进行替换等
System.out.println(body);
return body;
}
}

你可能感兴趣的:(java)