定义注解类:
@Target({ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface StrictEncryptedIdParam { String value(); String encryptedIdType(); boolean required() default true; String defaultValue() default " ue000ue001ue002 "; }
定义解析器:
public final class StrictEncryptedIdAnnotationResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter parameter) { return parameter.hasParameterAnnotation(StrictEncryptedIdParam.class); } @Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { if (parameter.getParameterType() != Long.class && parameter.getParameterType() != long.class) { throw new RuntimeException("EncryptedIdAnnotation must be on long field"); } HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest(); String idType = ""; String paramName = StringUtils.EMPTY; boolean isRequired = false; String defaultValue = ""; if (parameter.hasParameterAnnotation(StrictEncryptedIdParam.class)) { StrictEncryptedIdParam encryptedIdParam = parameter.getParameterAnnotation(StrictEncryptedIdParam.class); idType = encryptedIdParam.encryptedIdType(); paramName = encryptedIdParam.value(); isRequired = encryptedIdParam.required(); defaultValue = encryptedIdParam.defaultValue(); } if (StringUtils.isEmpty(paramName)) { paramName = parameter.getParameterName(); } String parameterValue = request.getParameter(paramName); if (StringUtils.isEmpty(parameterValue) || StringUtils.isEmpty(idType)) { if (!defaultValue.equals(ValueConstants.DEFAULT_NONE)) { return Long.parseLong(defaultValue); } if (isRequired) { throw new MissingServletRequestParameterException(paramName, parameter.getParameterType().getTypeName()); } return 0L; } if (StringUtils.isNumeric(parameterValue)) { throw new IllegalArgumentException("参数错误"); } if (parameterValue.length() < 8) { throw new IllegalArgumentException("参数错误"); } return resolveLong(parameterValue, idType, paramName); } private long resolveLong(String parameterValue, String idType, String paramName) { long decryptedId = IdEncryptor.decrypt(parameterValue, EncryptedIdType.of(idType)); if (!StringUtils.equals(String.valueOf(decryptedId), parameterValue)) { CommonWebScope.paramBundle().putDecryptedIdIntoParams(paramName, decryptedId); } return decryptedId; } }