filter 配置看上一篇 返回值格式不固定情况脱敏手机号等
@Override
public void doFilter(ServletRequest req, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException
{
HttpServletRequest request = (HttpServletRequest)req;
ResponseWrapper wrapperResponse = new ResponseWrapper((HttpServletResponse)response);//转换成代理类
filterChain.doFilter(request, wrapperResponse);
byte[] content = wrapperResponse.getContent();//获取返回值
if (content.length > 0)
{
String str = new String(content, "UTF-8");
StringBuilder sb = new StringBuilder(str);
boolean b = false;remoteAuthService.checkDataAccess("", "", "");
try
{
if (!b) {
Gson gson = new Gson();
Message message = gson.fromJson(str, Message.class);
Map data = (Map)message.getData();
Map pageInfo = (Map) data.get("pageInfo");
List list = (List) pageInfo.get("list");
//对实体进行脱敏
desensitizationObject(list);
str = gson.toJson(message);
}
}
catch (Exception e)
{
e.printStackTrace();
}
//把返回值输出到客户端
ServletOutputStream out = response.getOutputStream();
out.write( str.toString().getBytes());
out.flush();
}
}
//简单的脱敏方法 gson转换的都为map实体 想要修改哪个属性直接map.get(属性名字就好)
public void desensitization(List<Map> list) {
for (Map map:list) {
Field f1 = null;
try {
//f1 = o.getClass().getDeclaredField("idCardNo");
// f1.setAccessible(true);
String str ="";
String idCardNo = (String) map.get("idCardNo");
if (idCardNo.length()>=10){
String pre = idCardNo.substring(0, 3);
str+=pre;
String tail = idCardNo.substring(idCardNo.length() - 4, idCardNo.length());
for (int i = 3;i<idCardNo.length()-4;i++){
str+="*";
}
str+=tail;
}else{
String pre = idCardNo.substring(0, 1);
str+=pre;
String tail = idCardNo.substring(idCardNo.length() - 1, idCardNo.length());
for (int i = 1;i<idCardNo.length()-1;i++){
str+="*";
}
str+=tail;
}
map.put("idCardNo",str);
//修改这个字段的值
//f1.set(o,str);
} catch (Exception e) {
}
try {
// Field f2 = o.getClass().getDeclaredField("contactInfo");
//尝试获取字段中的值
// f2.setAccessible(true);
String contactInfo = (String) map.get("contactInfo");
String newContactInfo = contactInfo.substring(0, 3);
for (int j=3;j<contactInfo.length();j++){
newContactInfo+="*";
}
//f2.set(o,newContactInfo);
map.put("contactInfo",newContactInfo);
//查看这个字段的值
} catch (Exception e) {
//e.printStackTrace();
}
}
}
用Gson拿到需要修改的那个map实体 修改后返回前端