Java_經常使用工具類收集

1、日期工具類html

package com.ebd.application.common.utils;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.time.DateFormatUtils;

/**
 * 日期工具類, 繼承org.apache.commons.lang.time.DateUtils類
 */
public class DateUtils extends org.apache.commons.lang.time.DateUtils {

	private static String[] parsePatterns = { "yyyy-MM-dd",
			"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd",
			"yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" };

	/**
	 * 獲得當前日期字符串 格式(yyyy-MM-dd)
	 */
	public static String getDate() {
		return getDate("yyyy-MM-dd");
	}
	
	/**
	 * Timestamp to Date String
	 */
	public static String timestamptoString(Long timestampStr) {
		Timestamp ts = new Timestamp(timestampStr);   
        String dateStr = "";   
        DateFormat sdf = new SimpleDateFormat(parsePatterns[1]);   
        try {   
            dateStr = sdf.format(ts);   
        } catch (Exception e) {   
            e.printStackTrace();   
        }
        return dateStr;
	}

	/**
	 * 獲得當前日期字符串 格式(yyyy-MM-dd) pattern能夠爲:"yyyy-MM-dd" "HH:mm:ss" "E"
	 */
	public static String getDate(String pattern) {
		return DateFormatUtils.format(new Date(), pattern);
	}

	/**
	 * 獲得日期字符串 默認格式(yyyy-MM-dd) pattern能夠爲:"yyyy-MM-dd" "HH:mm:ss" "E"
	 */
	public static String formatDate(Date date, Object... pattern) {
		String formatDate = null;
		if (pattern != null && pattern.length > 0) {
			formatDate = DateFormatUtils.format(date, pattern[0].toString());
		} else {
			formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
		}
		return formatDate;
	}

	/**
	 * 獲得日期時間字符串,轉換格式(yyyy-MM-dd HH:mm:ss)
	 */
	public static String formatDateTime(Date date) {
		return formatDate(date, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 獲得當前時間字符串 格式(HH:mm:ss)
	 */
	public static String getTime() {
		return formatDate(new Date(), "HH:mm:ss");
	}

	/**
	 * 獲得當前日期和時間字符串 格式(yyyy-MM-dd HH:mm:ss)
	 */
	public static String getDateTime() {
		return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 獲得當前年份字符串 格式(yyyy)
	 */
	public static String getYear() {
		return formatDate(new Date(), "yyyy");
	}

	/**
	 * 獲得當前月份字符串 格式(MM)
	 */
	public static String getMonth() {
		return formatDate(new Date(), "MM");
	}

	/**
	 * 獲得當天字符串 格式(dd)
	 */
	public static String getDay() {
		return formatDate(new Date(), "dd");
	}

	/**
	 * 獲得當前星期字符串 格式(E)星期幾
	 */
	public static String getWeek() {
		return formatDate(new Date(), "E");
	}

	/**
	 * 日期型字符串轉化爲日期 格式 { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
	 * "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" }
	 */
	public static Date parseDate(Object str) {
		if (str == null) {
			return null;
		}
		try {
			return parseDate(str.toString(), parsePatterns);
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 獲取過去的天數
	 * 
	 * @param date
	 * @return
	 */
	public static long pastDays(Date date) {
		long t = new Date().getTime() - date.getTime();
		return t / (24 * 60 * 60 * 1000);
	}

	public static Date getDateStart(Date date) {
		if (date == null) {
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			date = sdf.parse(formatDate(date, "yyyy-MM-dd") + " 00:00:00");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

	public static Date getDateEnd(Date date) {
		if (date == null) {
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			date = sdf.parse(formatDate(date, "yyyy-MM-dd") + " 23:59:59");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

}

2、文件目錄工具java

package com.ebd.application.common.utils;

import java.io.File;
import java.io.IOException;

public class CreateFileUtil {

	public static boolean createFile(String destFileName) {  
        File file = new File(destFileName);  
        if(file.exists()) {  
            System.out.println("建立單個文件" + destFileName + "失敗,目標文件已存在!");  
            return false;  
        }  
        if (destFileName.endsWith(File.separator)) {  
            System.out.println("建立單個文件" + destFileName + "失敗,目標文件不能爲目錄!");  
            return false;  
        }  
        //判斷目標文件所在的目錄是否存在  
        if(!file.getParentFile().exists()) {  
            //若是目標文件所在的目錄不存在,則建立父目錄  
            System.out.println("目標文件所在目錄不存在,準備建立它!");  
            if(!file.getParentFile().mkdirs()) {  
                System.out.println("建立目標文件所在目錄失敗!");  
                return false;  
            }  
        }  
        //建立目標文件  
        try {  
            if (file.createNewFile()) {  
                System.out.println("建立單個文件" + destFileName + "成功!");  
                return true;  
            } else {  
                System.out.println("建立單個文件" + destFileName + "失敗!");  
                return false;  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
            System.out.println("建立單個文件" + destFileName + "失敗!" + e.getMessage());  
            return false;  
        }  
    }  
     
     
    public static boolean createDir(String destDirName) {  
        File dir = new File(destDirName);  
        if (dir.exists()) {  
            System.out.println(destDirName + "目錄已經存在");  
            return true;  
        }  
        if (!destDirName.endsWith(File.separator)) {  
            destDirName = destDirName + File.separator;  
        }  
        //建立目錄  
        if (dir.mkdirs()) {  
            System.out.println("建立目錄" + destDirName + "成功!");  
            return true;  
        } else {  
            System.out.println("建立目錄" + destDirName + "失敗!");  
            return false;  
        }  
    }  
     
     
    public static String createTempFile(String prefix, String suffix, String dirName) {  
        File tempFile = null;  
        if (dirName == null) {  
            try{  
                //在默認文件夾下建立臨時文件  
                tempFile = File.createTempFile(prefix, suffix);  
                //返回臨時文件的路徑  
                return tempFile.getCanonicalPath();  
            } catch (IOException e) {  
                e.printStackTrace();  
                System.out.println("建立臨時文件失敗!" + e.getMessage());  
                return null;  
            }  
        } else {  
            File dir = new File(dirName);  
            //若是臨時文件所在目錄不存在,首先建立  
            if (!dir.exists()) {  
                if (!CreateFileUtil.createDir(dirName)) {  
                    System.out.println("建立臨時文件失敗,不能建立臨時文件所在的目錄!");  
                    return null;  
                }  
            }  
            try {  
                //在指定目錄下建立臨時文件  
                tempFile = File.createTempFile(prefix, suffix, dir);  
                return tempFile.getCanonicalPath();  
            } catch (IOException e) {  
                e.printStackTrace();  
                System.out.println("建立臨時文件失敗!" + e.getMessage());  
                return null;  
            }  
        }  
    }  
     
    public static void main(String[] args) {  
        //建立目錄  
        String dirName = "D:/work/temp/temp0/temp1";  
        CreateFileUtil.createDir(dirName);  
        //建立文件  
        String fileName = dirName + "/temp2/tempFile.txt";  
        CreateFileUtil.createFile(fileName);  
        //建立臨時文件  
        String prefix = "temp";  
        String suffix = ".txt";  
        for (int i = 0; i < 10; i++) {  
            System.out.println("建立了臨時文件:"  
                    + CreateFileUtil.createTempFile(prefix, suffix, dirName));  
        }  
        //在默認目錄下建立臨時文件  
        for (int i = 0; i < 10; i++) {  
            System.out.println("在默認目錄下建立了臨時文件:"  
                    + CreateFileUtil.createTempFile(prefix, suffix, null));  
        }  
    }  
}

3、中文判斷工具類 python

package com.ebd.application.common.utils;

import java.util.regex.Pattern;

/**
 * 中文判斷工具類 
 * @author Administrator
 */
public class CharUtil {
	 
    public static void main(String[] args) {
        String[] strArr = new String[] { "www.micmiu.com", "!@#$%^&*()_+{}[]|\"'?/:;<>,.", "!¥……()——:;「」‘’《》,。?、", "不要啊", "やめて", "韓佳人", "???" };
        for (String str : strArr) {
            System.out.println("===========> 測試字符串:" + str);
            System.out.println("正則判斷結果:" + isChineseByREG(str) + " -- " + isChineseByName(str));
            System.out.println("Unicode判斷結果 :" + isChinese(str));
            System.out.println("詳細判斷列表:");
            char[] ch = str.toCharArray();
            for (int i = 0; i < ch.length; i++) {
                char c = ch[i];
                System.out.println(c + " --> " + (isChinese(c) ? "是" : "否"));
            }
        }
    }
 
    // 根據Unicode編碼完美的判斷中文漢字和符號
    private static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
            return true;
        }
        return false;
    }
 
    // 完整的判斷中文漢字和符號
    public static boolean isChinese(String strName) {
        char[] ch = strName.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            char c = ch[i];
            if (isChinese(c)) {
                return true;
            }
        }
        return false;
    }
 
    // 只能判斷部分CJK字符(CJK統一漢字)
    public static boolean isChineseByREG(String str) {
        if (str == null) {
            return false;
        }
        Pattern pattern = Pattern.compile("[\\u4E00-\\u9FBF]+");
        return pattern.matcher(str.trim()).find();
    }
 
    // 只能判斷部分CJK字符(CJK統一漢字)
    public static boolean isChineseByName(String str) {
        if (str == null) {
            return false;
        }
        // 大小寫不一樣:\\p 表示包含,\\P 表示不包含
        // \\p{Cn} 的意思爲 Unicode 中未被定義字符的編碼,\\P{Cn} 就表示 Unicode中已經被定義字符的編碼
        String reg = "\\p{InCJK Unified Ideographs}&&\\P{Cn}";
        Pattern pattern = Pattern.compile(reg);
        return pattern.matcher(str.trim()).find();
    }
}

 4、文件上傳工具mysql

package com.ebd.application.common.utils;

import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

public class FileUploadUtils {
	
	public static final String UPLOAD_URL  = "c:/pp";
	
	/**
	 * 上傳圖片,圖片的名稱filename是根據時間+隨機數組裝成的
	 * @param file MultipartFile file
	 * @param request HttpServletRequest request,
	 * @param uploadDir 上傳的目的文件夾
	 * @return 返回文件的上傳地址 (uploadDir/filename)
	 */
	public static String upload(MultipartFile file, HttpServletRequest request,String uploadDir) {
		String logoUrl = null;
		if (file != null && !file.isEmpty()) {
			System.out.println(request.getSession().getServletContext());
			String filePath = request.getSession().getServletContext()
					.getRealPath(uploadDir);
			
			//目錄不存在時,新建目錄
			createDirectory(filePath);
			
			//獲得原圖片的後綴名
			String srcfilename = file.getOriginalFilename();
			String suffix=srcfilename.substring(srcfilename.lastIndexOf("."));
			//組裝新圖片的名稱
			 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		     String format = dateFormat.format(new Date());
		    
			String filename = format+ new Random().nextInt(1000000)+suffix;
			
			File destFile = new File(filePath, filename);
			//若是文件存在,繼續隨機名稱
			while(destFile.exists()){
				filename = format+ new Random().nextInt(1000000)+suffix;
				destFile = new File(filePath, filename);
			}
			
			try {
				file.transferTo(destFile);
				logoUrl = uploadDir + "/" + filename;
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return logoUrl;
	}
	
	/**
	 * 上傳文件,文件名爲源文件的名稱
	 * @param file
	 * @param request
	 * @param uploadDir
	 * @return 上傳文件的路徑:uploadDir + "/" + srcfilename
	 */
	public static String uploadFile(MultipartFile file, HttpServletRequest request,String uploadDir) {
		String logoUrl = null;
		if (file != null && !file.isEmpty()) {
			//獲取上傳文件夾的真實地址
			String dirPath = request.getSession().getServletContext()
					.getRealPath(uploadDir);
			
			//目錄不存在時,新建目錄
			createDirectory(dirPath);
			
			//獲得源文件的名稱
			String srcfilename = file.getOriginalFilename();
			
			//構建目標文件
			File destFile = new File(dirPath, srcfilename);
			try {
				//上傳文件
				file.transferTo(destFile);
				logoUrl = uploadDir + "/" + srcfilename;
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return logoUrl;
	}
	
	/**
	 * 新建目錄
	 * @param dirPath
	 */
	public static void createDirectory(String dirPath){
		if(StringUtils.isNotBlank(dirPath)){
			// 得到文件對象  
			File file = new File(dirPath);
			if(!file.exists()){
				// 若是路徑不存在,則建立  
				file.mkdirs();
			}
		}
	}
	
	/** 
	 * 刪除單個文件 
	 * @param   path    被刪除文件的文件名 
	 * @return 單個文件刪除成功返回true,不然返回false 
	 */  
	public static boolean deleteFile(String path){
		boolean flag = false;
		File file = new File(path);
		// 路徑爲文件且不爲空則進行刪除  
		if(file.isFile() && file.exists()){
			file.delete();
			flag = true;
		}
		
		return flag;
	}
	
	/**
     * 生產縮略圖
     * @param src 原圖
     * @param dir 縮略圖
     * @param fileName 縮略圖名稱
     * @return
     */
    public static String thumb(File src,File dir,String fileName,int nw,int nh){
    	
    	 try {  
             /* 
             AffineTransform 類表示 2D 仿射變換,它執行從 2D 座標到其餘 2D 
                                      座標的線性映射,保留了線的「直線性」和「平行性」。能夠使用一系 
                                      列平移、縮放、翻轉、旋轉和剪切來構造仿射變換。 
             */  
             AffineTransform transform = new AffineTransform();
             //讀取圖片  
             BufferedImage bis = ImageIO.read(src); 
             int w = bis.getWidth();  
             int h = bis.getHeight();  
             double sx = (double)nw/w;  
             double sy = (double)nh/h;  
             //將此變換設置爲縮放變換。  
             transform.setToScale(sx,sy); 
             /* 
              * AffineTransformOp類使用仿射轉換來執行從源圖像或 Raster 中 2D 座標到目標圖像或 
              * Raster 中 2D 座標的線性映射。所使用的插值類型由構造方法經過 
              * 一個 RenderingHints 對象或經過此類中定義的整數插值類型之一來指定。 
			  * 若是在構造方法中指定了 RenderingHints 對象,則使用插值提示和呈現 
			  * 的質量提示爲此操做設置插值類型。要求進行顏色轉換時,能夠使用顏色 
			  * 呈現提示和抖動提示。 注意,務必要知足如下約束:源圖像與目標圖像 
			  * 必須不一樣。 對於 Raster 對象,源圖像中的 band 數必須等於目標圖像中 
			  * 的 band 數。 
             */  
             AffineTransformOp ato = new AffineTransformOp(transform,null);  
             BufferedImage bid = new BufferedImage(nw,nh,BufferedImage.TYPE_3BYTE_BGR);  
             /* 
              * TYPE_3BYTE_BGR 表示一個具備 8 位 RGB 顏色份量的圖像, 
              * 對應於 Windows 風格的 BGR 顏色模型,具備用 3 字節存 
              * 儲的 Blue、Green 和 Red 三種顏色。 
             */  
             ato.filter(bis,bid);  
             ImageIO.write(bid,"jpeg",dir);  
         } catch(Exception e) {  
             e.printStackTrace();  
         }  
    	
    	 return  dir + "/" + fileName;
    }
	
	
	 /** 
     * 複製整個文件夾內容 
     * @param oldPath 
     * @param newPath 
     * @return boolean 
     */ 
   public static void copyFolder(String oldPath, String newPath) {

       try { 
    	   //若是文件夾不存在 則創建新文件夾 
           (new File(newPath)).mkdirs(); 
           File a=new File(oldPath); 
           String[] file=a.list(); 
           File temp=null; 
           for (int i = 0; i < file.length; i++) { 
               if(oldPath.endsWith(File.separator)){ 
                   temp=new File(oldPath+file[i]); 
               } 
               else{ 
                   temp=new File(oldPath+File.separator+file[i]); 
               }

               if(temp.isFile()){ 
                   FileInputStream input = new FileInputStream(temp); 
                   FileOutputStream output = new FileOutputStream(newPath + "/" + 
                           (temp.getName()).toString()); 
                   byte[] b = new byte[1024 * 5]; 
                   int len; 
                   while ( (len = input.read(b)) != -1) { 
                       output.write(b, 0, len); 
                   } 
                   output.flush(); 
                   output.close(); 
                   input.close(); 
               } 
               if(temp.isDirectory()){//若是是子文件夾 
                   copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]); 
               } 
           } 
       } 
       catch (Exception e) { 
           System.out.println("複製整個文件夾內容操做出錯"); 
           e.printStackTrace();

       }

   }
   
   /** 
    * 刪除文件夾 
    * @param filePathAndName
    * @param fileContent
    * @return boolean 
    */ 
  public static void delFolder(String folderPath) { 
      try { 
          delAllFile(folderPath); //刪除完裏面全部內容 
          String filePath = folderPath; 
          filePath = filePath.toString(); 
          java.io.File myFilePath = new java.io.File(filePath); 
          myFilePath.delete(); //刪除空文件夾

      } 
      catch (Exception e) { 
          System.out.println("刪除文件夾操做出錯"); 
          e.printStackTrace();

      }

  }

  /** 
    * 刪除文件夾裏面的全部文件 
    * @param path
    */ 
  public static void delAllFile(String path) { 
      File file = new File(path); 
      if (!file.exists()) { 
          return; 
      } 
      if (!file.isDirectory()) { 
          return; 
      } 
      String[] tempList = file.list(); 
      File temp = null; 
      for (int i = 0; i < tempList.length; i++) { 
          if (path.endsWith(File.separator)) { 
              temp = new File(path + tempList[i]); 
          } 
          else { 
              temp = new File(path + File.separator + tempList[i]); 
          } 
          if (temp.isFile()) { 
              temp.delete(); 
          } 
          if (temp.isDirectory()) { 
              delAllFile(path+"/"+ tempList[i]);//先刪除文件夾裏面的文件 
              delFolder(path+"/"+ tempList[i]);//再刪除空文件夾 
          } 
      } 
    }
  
	  /** 
	   * 移動文件到指定目錄 
	   * @param oldPath
	   * @param newPath 
	   */ 
	public static void moveFile(String oldPath, String newPath) { 
		copyFolder(oldPath, newPath); 
		delFolder(oldPath);
	
	}
	
	public static void main(String[] args) {

		//		System.out.println(new Date().getTime());
//		System.out.println(String.valueOf(new Date().getTime()));
////		File f =new File("TileTest.doc");
//	      String fileName="TileTest....6.6doc";
//	      String prefix=fileName.substring(fileName.lastIndexOf("."));
//	      System.out.println(prefix);
//	      System.out.println(new Random().nextInt(1000000));
//	      System.out.println(new Random().nextInt(1000000));
//	      File f = new File("d:/1.txt");
//	      System.out.println(f.exists());
		
		File src = new File("D:\\dcd01448724c402a8cf8b852e1307510\\qrcode_for_gh_cf64bce34a18_344.jpg");
		File dir = new File("D:\\dcd01448724c402a8cf8b852e1307510");
//		File src = new File("D:\\architecture\\vungu\\workspace0428\\vp-standweb\\src\\main\\webapp\\fileUpload\\images\\subscribe\\dcd01448724c402a8cf8b852e1307510\\20160120171448178836077.png");
//		File dir = new File("D:\\architecture\\vungu\\workspace0428\\vp-standweb\\src\\main\\webapp\\fileUpload\\images\\subscribe\\dcd01448724c402a8cf8b852e1307510");
		String fileName = "20160120171448178836077thumb.jpg";
		int nw=360;
		int nh=200;
		thumb(src, dir, fileName, nw, nh);
	}
}

5、UUID簡單工具web

package com.ebd.application.common.utils;

import java.security.SecureRandom;
import java.util.UUID;

public class Identities {
	
	private static SecureRandom random = new SecureRandom();
	
	public static String uuid() {
	    return UUID.randomUUID().toString().replaceAll("-", "");
	}

	public static long randomLong() {
		return Math.abs(random.nextLong());
	}

}

6、JDBC工具ajax

package com.ebd.application.common.utils;

import java.lang.reflect.Field;  
import java.sql.Connection;  
import java.sql.DriverManager;  
import java.sql.PreparedStatement;  
import java.sql.ResultSet;  
import java.sql.ResultSetMetaData;  
import java.sql.SQLException;  
import java.util.ArrayList;  
import java.util.HashMap;  
import java.util.List;  
import java.util.Map;  

/**
 * JDBC工具類
 * @author Administrator
 */
public class JdbcUtils {

    //數據庫用戶名  
    private static final String USERNAME = "root";  
    //數據庫密碼  
    private static final String PASSWORD = "root";  
    //驅動信息   
    private static final String DRIVER = "com.mysql.jdbc.Driver";  
    //數據庫地址  
    private static final String URL = "jdbc:mysql://localhost:3306/test";  
    private Connection connection;  
    private PreparedStatement pstmt;  
    private ResultSet resultSet;  
    public JdbcUtils() {  
        // TODO Auto-generated constructor stub  
        try{  
            Class.forName(DRIVER);  
            System.out.println("數據庫鏈接成功!");  
  
        }catch(Exception e){  
  
        }  
    }  
      
    /** 
     * 得到數據庫的鏈接 
     * @return 
     */  
    public Connection getConnection(){  
        try {  
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);  
        } catch (SQLException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        return connection;  
    }  
  
      
    /** 
     * 增長、刪除、改 
     * @param sql 
     * @param params 
     * @return 
     * @throws SQLException 
     */  
    public boolean updateByPreparedStatement(String sql, List<Object> params)throws SQLException{  
        boolean flag = false;  
        int result = -1;  
        pstmt = connection.prepareStatement(sql);  
        int index = 1;  
        if(params != null && !params.isEmpty()){  
            for(int i=0; i<params.size(); i++){  
                pstmt.setObject(index++, params.get(i));  
            }  
        }  
        result = pstmt.executeUpdate();  
        flag = result > 0 ? true : false;  
        return flag;  
    }  
  
    /** 
     * 查詢單條記錄 
     * @param sql 
     * @param params 
     * @return 
     * @throws SQLException 
     */  
    public Map<String, Object> findSimpleResult(String sql, List<Object> params) throws SQLException{  
        Map<String, Object> map = new HashMap<String, Object>();  
        int index  = 1;  
        pstmt = connection.prepareStatement(sql);  
        if(params != null && !params.isEmpty()){  
            for(int i=0; i<params.size(); i++){  
                pstmt.setObject(index++, params.get(i));  
            }  
        }  
        resultSet = pstmt.executeQuery();//返回查詢結果  
        ResultSetMetaData metaData = resultSet.getMetaData();  
        int col_len = metaData.getColumnCount();  
        while(resultSet.next()){  
            for(int i=0; i<col_len; i++ ){  
                String cols_name = metaData.getColumnName(i+1);  
                Object cols_value = resultSet.getObject(cols_name);  
                if(cols_value == null){  
                    cols_value = "";  
                }  
                map.put(cols_name, cols_value);  
            }  
        }  
        return map;  
    }  
  
    /**查詢多條記錄 
     * @param sql 
     * @param params 
     * @return 
     * @throws SQLException 
     */  
    public List<Map<String, Object>> findModeResult(String sql, List<Object> params) throws SQLException{  
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();  
        int index = 1;  
        pstmt = connection.prepareStatement(sql);  
        if(params != null && !params.isEmpty()){  
            for(int i = 0; i<params.size(); i++){  
                pstmt.setObject(index++, params.get(i));  
            }  
        }  
        resultSet = pstmt.executeQuery();  
        ResultSetMetaData metaData = resultSet.getMetaData();  
        int cols_len = metaData.getColumnCount();  
        while(resultSet.next()){  
            Map<String, Object> map = new HashMap<String, Object>();  
            for(int i=0; i<cols_len; i++){  
                String cols_name = metaData.getColumnName(i+1);  
                Object cols_value = resultSet.getObject(cols_name);  
                if(cols_value == null){  
                    cols_value = "";  
                }  
                map.put(cols_name, cols_value);  
            }  
            list.add(map);  
        }  
  
        return list;  
    }  
  
    /**經過反射機制查詢單條記錄 
     * @param sql 
     * @param params 
     * @param cls 
     * @return 
     * @throws Exception 
     */  
    public <T> T findSimpleRefResult(String sql, List<Object> params,  
            Class<T> cls )throws Exception{  
        T resultObject = null;  
        int index = 1;  
        pstmt = connection.prepareStatement(sql);  
        if(params != null && !params.isEmpty()){  
            for(int i = 0; i<params.size(); i++){  
                pstmt.setObject(index++, params.get(i));  
            }  
        }  
        resultSet = pstmt.executeQuery();  
        ResultSetMetaData metaData  = resultSet.getMetaData();  
        int cols_len = metaData.getColumnCount();  
        while(resultSet.next()){  
            //經過反射機制建立一個實例  
            resultObject = cls.newInstance();  
            for(int i = 0; i<cols_len; i++){  
                String cols_name = metaData.getColumnName(i+1);  
                Object cols_value = resultSet.getObject(cols_name);  
                if(cols_value == null){  
                    cols_value = "";  
                }  
                Field field = cls.getDeclaredField(cols_name);  
                field.setAccessible(true); //打開javabean的訪問權限  
                field.set(resultObject, cols_value);  
            }  
        }  
        return resultObject;  
  
    }  
  
    /**經過反射機制查詢多條記錄 
     * @param sql  
     * @param params 
     * @param cls 
     * @return 
     * @throws Exception 
     */  
    public <T> List<T> findMoreRefResult(String sql, List<Object> params,  
            Class<T> cls )throws Exception {  
        List<T> list = new ArrayList<T>();  
        int index = 1;  
        pstmt = connection.prepareStatement(sql);  
        if(params != null && !params.isEmpty()){  
            for(int i = 0; i<params.size(); i++){  
                pstmt.setObject(index++, params.get(i));  
            }  
        }  
        resultSet = pstmt.executeQuery();  
        ResultSetMetaData metaData  = resultSet.getMetaData();  
        int cols_len = metaData.getColumnCount();  
        while(resultSet.next()){  
            //經過反射機制建立一個實例  
            T resultObject = cls.newInstance();  
            for(int i = 0; i<cols_len; i++){  
                String cols_name = metaData.getColumnName(i+1);  
                Object cols_value = resultSet.getObject(cols_name);  
                if(cols_value == null){  
                    cols_value = "";  
                }  
                Field field = cls.getDeclaredField(cols_name);  
                field.setAccessible(true); //打開javabean的訪問權限  
                field.set(resultObject, cols_value);  
            }  
            list.add(resultObject);  
        }  
        return list;  
    }  
  
    /** 
     * 釋放數據庫鏈接 
     */  
    public void releaseConn(){  
        if(resultSet != null){  
            try{  
                resultSet.close();  
            }catch(SQLException e){  
                e.printStackTrace();  
            }  
        }  
    }  
  
    /** 
     * @param args 
     */  
    public static void main(String[] args) throws SQLException {  
        // TODO Auto-generated method stub  
        JdbcUtils jdbcUtils = new JdbcUtils();  
        jdbcUtils.getConnection();  
  
        /*******************增*********************/  
        /*      String sql = "insert into userinfo (username, pswd) values (?, ?), (?, ?), (?, ?)"; 
        List<Object> params = new ArrayList<Object>(); 
        params.add("小明"); 
        params.add("123xiaoming"); 
        params.add("張三"); 
        params.add("zhangsan"); 
        params.add("李四"); 
        params.add("lisi000"); 
        try { 
            boolean flag = jdbcUtils.updateByPreparedStatement(sql, params); 
            System.out.println(flag); 
        } catch (SQLException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        }*/  
  
  
        /*******************刪*********************/  
        //刪除名字爲張三的記錄  
        /*      String sql = "delete from userinfo where username = ?"; 
        List<Object> params = new ArrayList<Object>(); 
        params.add("小明"); 
        boolean flag = jdbcUtils.updateByPreparedStatement(sql, params);*/  
  
        /*******************改*********************/  
        //將名字爲李四的密碼改了  
        /*      String sql = "update userinfo set pswd = ? where username = ? "; 
        List<Object> params = new ArrayList<Object>(); 
        params.add("lisi88888"); 
        params.add("李四"); 
        boolean flag = jdbcUtils.updateByPreparedStatement(sql, params); 
        System.out.println(flag);*/  
  
        /*******************查*********************/  
        //不利用反射查詢多個記錄  
        /*      String sql2 = "select * from userinfo "; 
        List<Map<String, Object>> list = jdbcUtils.findModeResult(sql2, null); 
        System.out.println(list);*/  
  
        //利用反射查詢 單條記錄  
//        String sql = "select * from userinfo where username = ? ";  
//        List<Object> params = new ArrayList<Object>();  
//        params.add("李四");  
//        UserInfo userInfo;  
//        try {  
//            userInfo = jdbcUtils.findSimpleRefResult(sql, params, UserInfo.class);  
//            System.out.print(userInfo);  
//        } catch (Exception e) {  
//            // TODO Auto-generated catch block  
//            e.printStackTrace();  
//        }  
        
         String sql2 = "select * from student "; 
         List<Map<String, Object>> list = jdbcUtils.findModeResult(sql2, null); 
         System.out.println(list);
    }  
}

7、JsonUtilspring

package com.ebd.application.common.utils;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.BooleanUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

public class JsonUtil extends BaseController{

	@SuppressWarnings("unused")
	private HttpServletRequest request;
	private HttpServletResponse response ;
	
	public JsonUtil(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
	}

	/**
	 * ajax後臺封裝jsonString
	 * @param jsonStr
	 * @throws IOException
	 */
	public void sendJson(String jsonStr) throws IOException {
		
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.print(jsonStr);
		out.flush();
		out.close();
	}
	
	/**
	 * json字符串轉成Java的Array數組
	 * @param json
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static Object[] readJSON2Array(String json, Class clazz) {
		JSONArray jsonArray = JSONArray.fromObject(json);
		Object[] infoList = (Object[]) JSONArray.toArray(jsonArray, clazz);
		return infoList;
	}
	
	/**
	 * JSON字符串轉成Java的List集合
	 * @param json
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "deprecation" })
	public static List<?> readJSON2List(String json, Class clazz) {
		JSONArray jsonArray = JSONArray.fromObject(json);
		List<?> infoList = JSONArray.toList(jsonArray, clazz);
		return infoList;
	}
	
	/**
	 * JSON對象反序列化成Java對象
	 * @param json
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static Object readJSON2Bean(String json, Class clazz) {
		JSONObject jsonObject = JSONObject.fromObject(json);
		Object bean = JSONObject.toBean(jsonObject, clazz);
		return bean;
	}
	
	/**
	 * 生成json格式串
	 * @param bean
	 * @param isSeri
	 * @param isFix
	 * @return
	 */
	public static String writeBean2JSON(Object bean, boolean isSeri, boolean isFix) {
		if (bean == null) {
			return null;
		}
		String jsonStr = null;
		if (BooleanUtils.isTrue(isSeri)) {
			jsonStr = JSONSerializer.toJSON(bean).toString();
			if (BooleanUtils.isTrue(isFix)) {
				jsonStr = "[" + jsonStr + "]";
			}
		} else {
			if (BooleanUtils.isTrue(isFix)) {
				jsonStr = JSONArray.fromObject(bean).toString();
			} else {
				jsonStr = JSONObject.fromObject(bean).toString();
			}
		}
		return jsonStr;
	}
	
	/**
	 * List生成Json
	 * @param list
	 * @param isSeri
	 * @param isFix
	 * @return
	 */
	public static String writeList2JSON(List<?> list, boolean isSeri,
			boolean isFix) {
		if (list == null) {
			return null;
		}
		String jsonStr = null;
		if (BooleanUtils.isTrue(isSeri)) {// 須要序列化
			jsonStr = JSONSerializer.toJSON(list).toString();
			if (BooleanUtils.isTrue(isFix)) {
				jsonStr = "[" + jsonStr + "]";
			}
		} else {
			if (BooleanUtils.isTrue(isFix)) {
				jsonStr = JSONArray.fromObject(list).toString();
			} else {
				jsonStr = JSONObject.fromObject(list).toString();
			}
		}
		return jsonStr;
	}
	
	/**
	 * Map生成Json
	 * @param map
	 * @param isSeri
	 * @param isFix
	 * @return
	 */
	public static String writeMap2JSON(Map<String, Object> map, boolean isSeri,
			boolean isFix) {
		String jsonStr = null;
		if (BooleanUtils.isTrue(isSeri)) {// 序列化
			jsonStr = JSONSerializer.toJSON(map).toString();
			if (BooleanUtils.isTrue(isFix)) {
				jsonStr = "[" + jsonStr + "]";
			}
		} else {
			if (BooleanUtils.isTrue(isFix)) {
				jsonStr = JSONArray.fromObject(map).toString();
			} else {
				jsonStr = JSONObject.fromObject(map).toString();
			}
		}
		return jsonStr;
	}
	
	/**
	 * Json串轉爲Bean
	 * @param json
	 * @param clazz
	 * @param subList
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static Object readJSON2Bean(String json, Class clazz, Map<String, Object> subList) {
		JSONObject jsonObject = JSONObject.fromObject(json);
		Object bean = JSONObject.toBean(jsonObject, clazz, subList);
		return bean;
	}
}

8、SpringUtilssql

package com.ebd.application.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

public final class SpringUtils implements BeanFactoryPostProcessor {

	private static ConfigurableListableBeanFactory beanFactory; // Spring應用上下文環境

	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		SpringUtils.beanFactory = beanFactory;
	}

	/**
	 * 獲取對象
	 * @param name
	 * @return Object 一個以所給名字註冊的bean的實例
	 * @throws org.springframework.beans.BeansException
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) throws BeansException {
		return (T) beanFactory.getBean(name);
	}

	/**
	 * 獲取類型爲requiredType的對象
	 * @param clz
	 * @return
	 * @throws org.springframework.beans.BeansException
	 * 
	 */
	public static <T> T getBean(Class<T> clz) throws BeansException {
		T result = (T) beanFactory.getBean(clz);
		return result;
	}

	/**
	 * 若是BeanFactory包含一個與所給名稱匹配的bean定義,則返回true
	 * 
	 * @param name
	 * @return boolean
	 */
	public static boolean containsBean(String name) {
		return beanFactory.containsBean(name);
	}

	/**
	 * 判斷以給定名字註冊的bean定義是一個singleton仍是一個prototype。
	 * 若是與給定名字相應的bean定義沒有被找到,將會拋出一個異常(NoSuchBeanDefinitionException)
	 * 
	 * @param name
	 * @return boolean
	 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
	 * 
	 */
	public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
		return beanFactory.isSingleton(name);
	}

	/**
	 * @param name
	 * @return Class 註冊對象的類型
	 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
	 * 
	 */
	public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
		return beanFactory.getType(name);
	}

	/**
	 * 若是給定的bean名字在bean定義中有別名,則返回這些別名
	 * 
	 * @param name
	 * @return
	 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
	 * 
	 */
	public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
		return beanFactory.getAliases(name);
	}

}
相關文章
相關標籤/搜索