package com.poyee.aspectj; import com.poyee.annotation.I18n; import com.poyee.common.enums.I18nFormat; import com.poyee.util.ServletUtils; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.lang.reflect.Method; /** * 国际化切面类,用于处理国际化相关的逻辑 */ @Slf4j @Aspect @Component public class i18nAspect { // 配置织入点,针对使用了i18n注解的方法 @Pointcut("@annotation(com.poyee.annotation.I18n)") public void logPointCut() { } /** * 在控制器的方法执行前,处理国际化逻辑 * @param joinPoint 切入点对象,包含被拦截的方法信息 */ @Before("execution(public * com.poyee.controller.*.*(..))") // @Before("logPointCut()") public void doBefore(JoinPoint joinPoint) { Signature signature = joinPoint.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); checkI18n(method); } /** * 判断是否支持国际化,并根据情况设置会话属性 * @param method 被拦截的方法对象,用于获取注解信息 */ private void checkI18n(Method method) { if (method.isAnnotationPresent(I18n.class)) { I18n i18n = method.getAnnotation(I18n.class); HttpServletRequest request = ServletUtils.getRequest(); String language = request.getHeader("Accept-Language"); boolean isI18n = true; if(StringUtils.isBlank(language)) { language = LocaleContextHolder.getLocale().getLanguage(); isI18n = false; } try { HttpSession session = ServletUtils.getSession(false); if (session == null) { log.warn("Session is null, cannot set I18n attributes."); return; } // 根据方法上的i18n注解和请求头中的语言信息,决定是否启用国际化 if(i18n.value() && isI18n) { session.setAttribute("language", language); I18nFormat[] format = i18n.format(); if(format.length > 0) { session.setAttribute("i18nFormat", i18n.format()); if (log.isInfoEnabled()) { log.info("i18nFormat:{}", format[0].getMsg()); } } session.setAttribute("i18n", true); } else { // 如果 I18n.value() 为 false,但 isI18n 为 true,仍不启用国际化 session.setAttribute("i18n", false); } } catch (Exception e) { log.error("Failed to set I18n attributes", e); } } } }