废话就不多说了,看代码
package org.com.rsmall.wx.config.advice;
import org.apache.commons.lang3.StringUtils;
import org.com.rsmall.db.dao.member.MemberCompanyBindInfoDao;
import org.com.rsmall.db.dao.member.MemberDao;
import org.com.rsmall.db.entity.member.Member;
import org.com.rsmall.db.entity.member.MemberCompanyBindInfo;
import org.com.rsmall.wx.ann.RequestFilter;
import org.com.rsmall.wx.cache.MemberTokenCache;
import org.com.utils.AuthTokenUtils;
import org.com.web.WebResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
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.servlet.mvc.method.annotation.ResponseBodyAdvice;
import java.lang.reflect.Method;
import java.util.List;
/**
* @author yupanpan
* @Description:
* @date 2020/12/13 20:22
*/
@ControllerAdvice
public class ControllerResponseAdvice implements ResponseBodyAdvice {
@Autowired
private MemberDao memberDao;
@Autowired
private MemberCompanyBindInfoDao memberCompanyBindInfoDao;
@Override
public boolean supports(MethodParameter methodParameter, Class aClass) {
Method method = methodParameter.getMethod();
RequestFilter requestFilter = method.getAnnotation(RequestFilter.class);
if(requestFilter!=null){
//true说明是放行,则返回false不拦截
return !requestFilter.filter();
}
return true;
}
@Override
public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
HttpHeaders headers = serverHttpRequest.getHeaders();
List<String> multiValues = headers.get(MemberTokenCache.AUTHORIZATION_PROPERTY_MEMBERID);
if(multiValues!=null&&!multiValues.isEmpty()){
String memberId = multiValues.get(0);
Member member = memberDao.selectById(Long.valueOf(memberId));
List<MemberCompanyBindInfo> companys = memberCompanyBindInfoDao.getByMemberId(member.getId());
if(o instanceof WebResult){
WebResult result=(WebResult)o;
result.setMemberTel(StringUtils.isNotBlank(member.getTel())?member.getTel().trim():"");
result.setMemberType(member.getType());
if(companys!=null&&!companys.isEmpty()){
MemberCompanyBindInfo memberCompanyBindInfo = companys.get(0);
result.setMemberCompany(memberCompanyBindInfo.getCompanyName().trim());
}else {
result.setMemberCompany("");
}
}
}
return o;
}
}
package org.com.rsmall.wx.ann;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestFilter {
boolean filter() default true;
}
beforeBodyWrite方法是需要处理的逻辑