JAVA

1、获取登陆用户

public static User getUser(HttpServletRequest request) {
  Object obj = request.getSession().getAttribute("LOGON");
  return obj == null ? null : (User) obj;
 }

2、获取时间差(毫秒)

long startTime = System.currentTimeMillis();
conn = baseLogic.getConnection();
   creditorReport.reportCreditorInfo(conn);
   long endTime = System.currentTimeMillis();
   log.info("本次数据导入【定时任务】执行共花费时间:"+(endTime-startTime)+"毫秒!");

 

3、格式化数字为  40,000.00

 DecimalFormat format= new DecimalFormat("#,##0.00%");

String str=format.format((StringOperator.div(Double.parseDouble(dataArray[2]), Double.parseDouble(dataArray[1]), 4))); //通过件比例

public static double div(double v1,double v2,int scale){

       if(scale<0){

           throw new IllegalArgumentException("The scale must be a positive integer or zero");        }

       BigDecimal b1 = new BigDecimal(Double.toString(v1));        BigDecimal b2 = new BigDecimal(Double.toString(v2));

       return b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();    }

4、jdbc批量处理数据

 List<YQInfo> list = null;
  PreparedStatement ps =null;
  try {
     conn.setAutoCommit(false);

     list = queryInfo(conn);
         String sql = "INSERT INTO……";

   ps = conn.prepareStatement(sql);
   if(null!=list && list.size() > 0){
      for (int i = 0; i < list.size(); i++) {
         YQInfo yQInfo = list.get(i);
         ps.setString(1, yQInfo.getLoanContractNo());

      ps.addBatch();
     
         if((i+1)%1000==0){
            ps.executeBatch();
            conn.commit();
            ps.clearBatch();
         }
      }
    ps.executeBatch();

 }
   conn.commit();
  } catch (Exception e) {

    e.printStackTrace();
       log.info("逾期数据导入【定时任务】出现异常!");
       log.error("逾期数据导入【定时任务】出现异常,开始删除异常数据!");
       try {
          //删除插入的数据
          int result = deletetoDayData(conn);
          log.error("共删除"+result+"条数据!");
          conn.commit();
       } catch (Exception e1) {
            e1.printStackTrace();
       }
       throw new APSException(e);
  }finally{
   ObjectOperate.getInstance().ObjectFree(list);
   ObjectOperate.getInstance().closConn(ps,conn);
  }

 

/**
  * 对象指空
  * @param obj
  */
 public  void ObjectFree(Object ...obj) throws APSException {
  try {
     for (Object o : obj) {
        if (null != o) {
           o = null;
        }
     }
  } catch (Exception e) {
     StringBuffer erbuffer = new StringBuffer();
     erbuffer.append("对象指空异常!");
     log.error(erbuffer.toString(), e);
     throw new APSException(erbuffer.toString(), e);
    }
 }

 

/**
  * 关闭数据库
  *
  * @param rs
  * @param st
  * @param conn
  */
 public void closConn(Object ... objects) throws APSException {
  try {
     for (Object obj : objects) {
        if (obj instanceof ResultSet) {
           ((ResultSet) obj).close();
           continue;
        }
        if (obj instanceof Statement) {
           ((Statement) obj).close();
           continue;
        }
        if (obj instanceof PreparedStatement) {
           ((PreparedStatement) obj).close();
           continue;
        }
        if (obj instanceof Connection) {
           ((Connection) obj).close();
           continue;
        }
     }
  } catch (Exception e) {
       StringBuffer erbuffer = new StringBuffer();
       erbuffer.append("关闭数据库连接异常!");
       log.error(erbuffer.toString(), e);
       throw new APSException(erbuffer.toString(), e);
    }
 }

 

5、给一段代码加锁

try {
     synchronized (this) {

      业务处理代码……

   }

}

6、字符串判空

public static boolean isNull(String str) {
    if (null == str || str.equals("")) {
       return true;
    }
      return false;
 }

7、删除指定路径下的文件

//删除目录下文件
    public static void deletePath(String filepath) throws Exception {
     File f = new File(filepath);//定义文件路径         
        if(f.exists() && f.isDirectory()){//判断是文件还是目录  
        //若有则把文件放进数组,并判断是否有下级目录  
        File delFile[]=f.listFiles();  
        int i =f.listFiles().length;  
        for(int j=0;j<i;j++){  
            if(delFile[j].isDirectory()){  
             deletePath(delFile[j].getAbsolutePath());//递归调用del方法并取得子目录路径  
             }  
             delFile[j].delete();//删除文件  
        }
        }
    }

8、创建目录

public static void mkDirs(String filePath) {   

  // 判断路径是否存在   

  File directory = new File(filePath.toString());   

  if (directory.exists() && directory.isDirectory()) {

    }   else {    

   // 如果不存在则创建目录    

    directory.mkdirs();   

    }  

}

9、获取txt换行符

//获得换行符
 private String getTxtNewLine() {
    byte[] newLine = new byte[2];
    newLine[0]=0x0d;
    newLine[1]=0x0a;
    return new String(newLine);
 }

调用

  fos.write((detailInfo.toString() + getTxtNewLine()).getBytes());
    fos.flush();
    detailInfo = null;

10、后台格式化数字

 new DecimalFormat("##.00").format(amount);

11、结果集迭代

List<String> idCardList = new ArrayList<String>();
   String[] cardArray = idCard.split(",");
   for (String cardA : cardArray) {
    idCardList.add(cardA);
   }

 12、本月一号到今天的数据

if (CommonMethod.isNull(appForm.getBeginDate())) {
    queryCondition.append(" AND T.CREDIT_DATE>=TO_DATE('"+DateUtil.getFormatDateStr(new Date(), "yyyy-MM")+"-01','YYYY-MM-DD')");
   }
   if (CommonMethod.isNull(appForm.getEndDate())) {
    queryCondition.append(" AND T.CREDIT_DATE<=TO_DATE('"+DateUtil.getFormatDateStr(new Date(), "yyyy-MM-dd")+" 23:59:59','YYYY-MM-DD hh24:mi:ss')");
   }

13、通过request获取后台数据页面显示

后台

StringBuffer pathTemp = new StringBuffer();
   pathTemp.append("会话已失效,请<a href='");
   pathTemp.append(request.getContextPath());
   pathTemp.append("/logon.do?method=reLogin' target='_top'>重新登录</a>!");
   request.setAttribute("reason", pathTemp);

页面

 <td align="left" class="red">
                                             ${errors }<br/>
                                             <%=request.getAttribute("reason")%>
 </td>

14、sevletPath

String sevletPath = request.getServletPath();
sevletPath = sevletPath.substring(1, sevletPath.indexOf("."));

15、请求路径(端口号)及方法

String methodName = mapping.getParameter();

logger.info(this.getClass().getName() + " 方法=" + methodValue + "被调用");

 

String requestStr= request.getRequestURL().toString();
String systemType = request.getRequestURI().split("/")[1];
int pos=requestStr.lastIndexOf(":");
String urlPort=requestStr.substring(pos+1,pos+6);

你可能感兴趣的:(java)