@Service("accessLogService")
@Transactional
public class LogMessageServiceImpl extends BaseDaoServiceImpl<AccessLogMessage,Long> implements LogMessageService{
 @Autowired
 SplitHibernateInterceptor splitInter;
 @Autowired
 public BaseDaoImpl<AccessLogMessage> baseDao;
 /**
  * 根据当前月份
  */
 @Override
 public void addLog(AccessLogMessage message) {
  //要拦截的目标数据库名称
  splitInter.setTargetTableName("accesslog_message");
  //月份从0计算
  int month = Calendar.getInstance().get(Calendar.MONTH);
  if(month==0){
   //1月份
   baseDao.save(message);
  }else{
   splitInter.setSubTableName("accesslog_message"+month);
   SessionFactory sf= baseDao.getSessionFactory();
   Session session = sf.openSession(splitInter);
   try{
    session.save(message);
   }finally{
    session.close();
   }
  }
  
 }
}

 

@Service("splitInter")
public class SplitHibernateInterceptor extends EmptyInterceptor {
 private static final long serialVersionUID = 2293562313992510554L;

 private String targetTableName;// 目标母表名
 private String subTableName;// 操作子表名 ,与目标结构一样

 public SplitHibernateInterceptor() {
 }

 public java.lang.String onPrepareStatement(java.lang.String sql) {
  sql = sql.toLowerCase();
  sql = sql.replaceAll(targetTableName, subTableName);
  return sql;

 }

 public String getTargetTableName() {
  return targetTableName;
 }

 public void setTargetTableName(String targetTableName) {
  this.targetTableName = targetTableName;
 }

 public String getSubTableName() {
  return subTableName;
 }

 public void setSubTableName(String subTableName) {
  this.subTableName = subTableName;
 }

}

 

 

@Component("baseDaoService")
@Transactional
public class BaseDaoServiceImpl<T, K extends Serializable> implements
  BaseDaoService<T, K> {

 @Autowired
 public ExtendBaseDao<T, K> extendBaseDao;

 @Override
 public void add(T t) {
  extendBaseDao.save(t);
 }

 @Override
 public void delete(T t) {
  extendBaseDao.delete(t);
 }

 @Override
 public void update(T t) {
  extendBaseDao.update(t);
 }

 @Override
 public T get(Class<T> entityClass, K k) {
  return extendBaseDao.get(entityClass, k);
 }

 @Override
 public void deleteByHql(String hql ,Object... objects) {
  extendBaseDao.delete(hql, objects);
 }

 @Override
 public List<T> query(String hql, Object... objects) {
  return extendBaseDao.list(hql, objects);
 }

 @Override
 public void marge(T t) {
  extendBaseDao.merge(t);
 }

}

 

@Entity
@Table(name = "ACCESSLOG_MESSAGE")
public class AccessLogMessage {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Column(name = "id")
 private Long id;
 @Column(name = "requestURI", length = 250)
 private String requestURI;
 
 @Column(name = "requestTime", length = 30)
 private String requestTime;
 @Column(name = "requestParams", length = 1000)
 private String requestParams;
 @Column(name = "userName", length = 32)
 private String userName;

 

@SuppressWarnings("serial")
public class ViewJsonInterceptor implements Interceptor {
 @Autowired
 private MemcachedClient memcachedClient;
 private static final Logger logger = LoggerFactory
   .getLogger(ViewJsonInterceptor.class);

 @Override
 public void init() {
  logger.info("Json格式化拦截器启动!");
 }

 @Override
 public void destroy() {
  logger.info("Json格式化拦截器销毁!");
 }

 public HttpServletRequest getRequest(ActionInvocation invocation) {
  ActionContext context = invocation.getInvocationContext();
  HttpServletRequest request = (HttpServletRequest) context
    .get(StrutsStatics.HTTP_REQUEST);
  return request;
 }

 

public HttpServletResponse getResponse(ActionInvocation invocation) {
  ActionContext context = invocation.getInvocationContext();
  HttpServletResponse response = (HttpServletResponse) context
    .get(StrutsStatics.HTTP_RESPONSE);
  return response;
 }


 
 @Override
 public String intercept(ActionInvocation invocation) throws Exception {

HttpServletRequest request = getRequest(invocation);
  HttpServletResponse response = getResponse(invocation);
  response.setContentType("text/html;charset=UTF-8");
  // end
  Object action = invocation.getAction();
  String methodName = invocation.getProxy().getMethod();
  Method method = action.getClass().getDeclaredMethod(methodName, new Class[0]);
  
  //防止 重复参数,如果重复取第一个
  invocation.getInvocationContext().setParameters(InterceptorUtil.noRepeatParams(invocation));
  
  
  if (!(action instanceof BaseViewJsonAction)
    || !method.isAnnotationPresent(ViewJson.class)) {
   return invocation.invoke();
  }
  String voke = null;
  BaseViewJsonAction baseViewJsonAction = (BaseViewJsonAction) action;// ============检验当前访问在缓存中是否存在========================
  String memcachedSwitch = Switch.getInstance().getMemcachedSwitch();
  String cacheKey = "";
  if (Switch.OPEN.equals(memcachedSwitch) && method.isAnnotationPresent(MemCachedJson.class) ) {
   // 获取当前访问URL对应的缓存key
   cacheKey = InterceptorUtil.getCacheKey(invocation, request);
   logger.debug("[key=]" + cacheKey);
   String cacheValue = null;
   try {
    memcachedClient.setSanitizeKeys(true);
    cacheValue = memcachedClient.get(cacheKey);
    if (StringUtils.isNotBlank(cacheValue)) {
     // 缓存中已存在cacheKey的cacheValue,则直接返回
     //记录日志,并保存至数据库
     InterceptorUtil.log(request, invocation);
     response.getWriter().write(cacheValue);
     return null;
    }
   } catch (Exception e) {
    logger.error("memecached异常:", e.getMessage());
   }
  }

try {
   invocation.invoke();
   JsonViewMessage jsonMessage = baseViewJsonAction.getJsonViewMessage();
   String code = "" + jsonMessage.getRet();
   if (Switch.OPEN.equals(memcachedSwitch) && method.isAnnotationPresent(MemCachedJson.class)) {
    // 将返回的正确结果注入缓冲
    
    code = "" + jsonMessage.getRet();
    if ("0".equals(code)) {
     String returnValue = baseViewJsonAction.jsonViewAsString();
     try {
      memcachedClient.set(cacheKey, 0, returnValue);
     } catch (Exception e) {
      logger.error("memecached set 缓存异常:", e.getMessage());
     }
     
    }
    // 注入缓存完成
   }
   if ("0".equals(code)) {
    //记录日志,并保存至数据库
    InterceptorUtil.log(request, invocation);
   }else{
    if(!"1".equals(code)&&logger.isErrorEnabled()){
     logger.error("code:" + code + ";message:" + jsonMessage.getRetInfo());
     logger.error("调用"+invocation.getAction().getClass().getSimpleName()+"."+methodName+"()");
     String absUrl =ServletRequestUtil.getRequestURL(request);
     logger.error(IPRequest.getIpAddress(request)+"=>"+request.getMethod()+"请求地址:"+absUrl);
    }
   }

  } catch (BusinessException e) {
   if(!"0".equals(e.getCode())){
    if(logger.isErrorEnabled()){
     logger.error("code:" + e.getCode() + ";message:" + e.getMessage());
     logger.error("调用"+invocation.getAction().getClass().getSimpleName()+"."+methodName+"()");
     String absUrl =ServletRequestUtil.getRequestURL(request);
     logger.error(IPRequest.getIpAddress(request)+"=>"+request.getMethod()+"请求地址:"+absUrl);
    }
   }
   baseViewJsonAction.getJsonViewMessage().setResult(null);
   baseViewJsonAction.getJsonViewMessage().setRet(e.getCode());
   baseViewJsonAction.getJsonViewMessage().setRetInfo(e.getMessage());
   
   
   
  }  finally {
   baseViewJsonAction.writeJsonView();
  }
  return voke;

}

 

public void writeJsonView() {
  if (userDefinedJsonObject != null) {
   userDefinedJsonObject.put("ret", jsonViewMessage.getRet());
   userDefinedJsonObject.put("retInfo", jsonViewMessage.getRetInfo());
   JsonFormater.writeJsonValue(mapper, this.response,
     userDefinedJsonObject);
   return;
  }
  if (jsonViewMessage.getAlias() != null) {
   Map<String, Object> map = new HashMap<String, Object>(3);
   map.put("ret", jsonViewMessage.getRet());
   map.put("retInfo", jsonViewMessage.getRetInfo());
   map.put(jsonViewMessage.getAlias(), jsonViewMessage.getResult());
   JsonFormater.writeJsonValue(mapper, this.response, map);
   return;
  }
  JsonFormater.writeJsonValue(mapper, this.response, jsonViewMessage);
 }

 

<package name="BasePackage" extends="struts-default">
  <interceptors>
   <interceptor name="LogInterceptor" class="com.core.action.interceptor.LogInterceptor"/>
   <interceptor name="ViewJsonInterceptor" class="com.core.action.interceptor.ViewJsonInterceptor"/>
   <!--<interceptor name="ParamValidateInterceptor" class="com.core.interceptor.ParamValidateInterceptor"/>-->
   <interceptor-stack name="JsonInterceptorStack">
    <interceptor-ref name="LogInterceptor"/>
    <interceptor-ref name="ViewJsonInterceptor"/>
    <!--<interceptor-ref name="ParamValidateInterceptor"/>-->
    
    <interceptor-ref name="defaultStack"/>
   </interceptor-stack>
  </interceptors>
  <default-interceptor-ref name="JsonInterceptorStack"/>
  <default-action-ref name="notFound" />
      <action name="notFound">
       <result>/WEB-INF/404.jsp</result>
     </action>
 </package>