spring - YUHAO-ZX/StudyCollection GitHub Wiki
1.spring 拦截器,拦截请求
implements HandlerInterceptor
private void responseDirect(HttpServletResponse response,FinanceResult result){
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
try {
response.getOutputStream().write(result.toJson().getBytes("UTF-8"));
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
}
}
2.AOP
@Component
@Aspect
@Pointcut("execution(* com.jumei.finance.gateway.controller..*(..))")
public void aspect(){}
@Around("aspect()")
public Object around(JoinPoint joinPoint){
int startTime = TimeUtils.getUnixTime();
String uuid = null;
RequestPersistent requestPersistent = null;
try {
requestPersistent = getPersistentTag(joinPoint);
uuid = recordRequest(joinPoint, startTime,requestPersistent);
ProceedingJoinPoint proceedingJoinPoint = (ProceedingJoinPoint) joinPoint;
Object result = proceedingJoinPoint.proceed();
proceedingJoinPoint.getSignature().getName();
recordResult(result, uuid, startTime,requestPersistent);
return result;
} catch (Throwable e) {
logger.error("[GatewayAopService-around]ERROR uuid<{}>,startTime<{}>",uuid,startTime,e);
FinanceResult result = FinanceResult.fail(GatewayErrorCode.SYSTEM_ERROR);
if(uuid != null)
recordResult(result, uuid, startTime,requestPersistent);
return result;
}
}
3.controller参数解析器
implements HandlerMethodArgumentResolver
@Override
public boolean supportsParameter(MethodParameter parameter) {
/*
只有当接口参数有 FastJson 标注才进行转换
*/
return parameter.getParameterAnnotation(FastJson.class) != null;
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
/*
统一转换为 FinanceRequest 对象,返回作为入参,约定业务数据通过:bizContent,传入
*/
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
FinanceRequest pojo = toRequest(request);
Class type = (Class)((ParameterizedType)parameter.getGenericParameterType()).getActualTypeArguments()[0];
Object content = JSON.parseObject(request.getParameter("bizContent"),type);
pojo.setBizContent(content);
return pojo;
}
public FinanceRequest toRequest( HttpServletRequest request) throws IllegalAccessException {
FinanceRequest financeRequest = new FinanceRequest();
Field[] superFields = FinanceRequest.class.getSuperclass().getDeclaredFields();
fillParam(superFields,request,financeRequest);
return financeRequest;
}
private void fillParam(Field[] fields,HttpServletRequest request,Object reciever){
for(Field field :fields){
field.setAccessible(true);
String fieldName = field.getName();
if(request.getParameter(fieldName) != null){
field.set(reciever,request.getParameter(fieldName));
}
}
}