ssm項目開發通用base模塊和工具

controller層日期轉換通用類html

package cn.itcast.jk.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

/**
 * 
 * @ClassName:
 * @Description:
 * @Company:
 * @author :馮俊明
 * @date 2017-11-26 上午11:56:54
 */
public abstract class BaseController {
    @InitBinder
    //此方法用於日期的轉換,若是未加,當頁面日期格式轉換錯誤,將報400錯誤,實際是由於此方法
    public void initBinder(WebDataBinder binder) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(true);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}

 

dao通用類的接口和實現類java

package cn.itcast.jk.dao;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import cn.itcast.jk.pagination.Page;

/**
 * @Description: 泛型類,基礎的DAO接口
 * @Author:    nutony
 * @Company:    http://java.itcast.cn
 * @CreateDate:    2014-2-25
 */
public interface BaseDao<T> {
    public List<T> findPage(Page page);                //分頁查詢
    public List<T> find(Map paraMap);                //帶條件查詢,條件能夠爲null,既沒有條件;返回list對象集合
    public T get(Serializable id);                    //只查詢一個,經常使用於修改
    public void insert(T entity);                    //插入,用實體做爲參數
    public void update(T entity);                    //修改,用實體做爲參數
    public void deleteById(Serializable id);        //按id刪除,刪除一條;支持整數型和字符串類型ID
    public void delete(Serializable[] ids);            //批量刪除;支持整數型和字符串類型ID
}
package cn.itcast.jk.dao.impl;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;

import cn.itcast.jk.dao.BaseDao;
import cn.itcast.jk.pagination.Page;

public abstract class BaseDaoImpl<T> extends SqlSessionDaoSupport implements BaseDao<T>{
    @Autowired
    //mybatis-spring 1.0無需此方法;mybatis-spring1.2必須注入。
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory){
        super.setSqlSessionFactory(sqlSessionFactory);
    }
    
    private String ns;        //命名空間
    public String getNs() {
        return ns;
    }
    public void setNs(String ns) {
        this.ns = ns;
    }
    
    public List<T> findPage(Page page){
        List<T> oList = this.getSqlSession().selectList(ns + ".findPage", page);
        return oList;
    }

    public List<T> find(Map map) {
        List<T> oList = this.getSqlSession().selectList(ns + ".find", map);
        return oList;
    }
    public T get(Serializable id) {
        return this.getSqlSession().selectOne(ns + ".get", id);
    }

    public void insert(T entity) {
        this.getSqlSession().insert(ns + ".insert", entity);
    }

    public void update(T entity) {
        this.getSqlSession().update(ns + ".update", entity);
    }

    public void deleteById(Serializable id) {
        this.getSqlSession().delete(ns + ".deleteById", id);
    }

    public void delete(Serializable[] ids) {
        this.getSqlSession().delete(ns + ".delete", ids);
    }
}

 

文件下載工具類mysql

 

package cn.itcast.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

public class DownloadUtil {
    
    /**
     * @param filePath 要下載的文件路徑
     * @param returnName 返回的文件名
     * @param response HttpServletResponse
     * @param delFlag 是否刪除文件
     */
    protected void download(String filePath,String returnName,HttpServletResponse response,boolean delFlag){
        this.prototypeDownload(new File(filePath), returnName, response, delFlag);
    }


    /**
     * @param file 要下載的文件
     * @param returnName 返回的文件名
     * @param response HttpServletResponse
     * @param delFlag 是否刪除文件
     */
    protected void download(File file,String returnName,HttpServletResponse response,boolean delFlag){
        this.prototypeDownload(file, returnName, response, delFlag);
    }
    
    /**
     * @param file 要下載的文件
     * @param returnName 返回的文件名
     * @param response HttpServletResponse
     * @param delFlag 是否刪除文件
     */
    public void prototypeDownload(File file,String returnName,HttpServletResponse response,boolean delFlag){
        // 下載文件
        FileInputStream inputStream = null;
        ServletOutputStream outputStream = null;
        try {
            if(!file.exists()) return;
            response.reset();
            //設置響應類型    PDF文件爲"application/pdf",WORD文件爲:"application/msword", EXCEL文件爲:"application/vnd.ms-excel"。  
            response.setContentType("application/octet-stream;charset=utf-8");

            //設置響應的文件名稱,並轉換成中文編碼
            //returnName = URLEncoder.encode(returnName,"UTF-8");
            returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1"));    //保存的文件名,必須和頁面編碼一致,不然亂碼
            
            //attachment做爲附件下載;inline客戶端機器有安裝匹配程序,則直接打開;注意改變配置,清除緩存,不然可能不能看到效果
            response.addHeader("Content-Disposition",   "attachment;filename="+returnName);  
            
            //將文件讀入響應流
            inputStream = new FileInputStream(file);
            outputStream = response.getOutputStream();
            int length = 1024;
            int readLength=0;
            byte buf[] = new byte[1024];
            readLength = inputStream.read(buf, 0, length);
            while (readLength != -1) {
                outputStream.write(buf, 0, readLength);
                readLength = inputStream.read(buf, 0, length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //刪除原文件
            
            if(delFlag) {                
                file.delete();
            }
        }
    }

    /**
     * by tony 2013-10-17
     * @param byteArrayOutputStream 將文件內容寫入ByteArrayOutputStream
     * @param response HttpServletResponse    寫入response
     * @param returnName 返回的文件名
     */
    public void download(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName) throws IOException{
        response.setContentType("application/octet-stream;charset=utf-8");
        returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1"));            //保存的文件名,必須和頁面編碼一致,不然亂碼
        response.addHeader("Content-Disposition",   "attachment;filename=" + returnName);  
        response.setContentLength(byteArrayOutputStream.size());
        
        ServletOutputStream outputstream = response.getOutputStream();    //取得輸出流
        byteArrayOutputStream.writeTo(outputstream);                    //寫到輸出流
        byteArrayOutputStream.close();                                    //關閉
        outputstream.flush();                                            //刷數據
    }
}

 購銷合同模塊映射文件做爲例子web

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="cn.itcast.jk.mapper.ContractMapper">
    <!-- resultMap映射 合同-->
    <resultMap type="cn.itcast.jk.domain.Contract" id="contractRM">
        <!-- 主鍵 -->
        <id property="id" column="CONTRACT_ID"/>
        <!-- 通常屬性 -->
        <result property="offeror" column="OFFEROR"/>
        <result property="contractNo" column="CONTRACT_NO"/>
        
        <!--虛擬字段  -->
        <result property="cpnumber" column="CPNUMBER"/>
        <result property="extnumber" column="EXTNUMBER"/>
        
        <result property="signingDate" column="SIGNING_DATE"/>
        <result property="inputBy" column="INPUT_BY"/>
        <result property="checkBy" column="CHECK_BY"/>
        <result property="inspector" column="INSPECTOR"/>
        <result property="totalAmount" column="TOTAL_AMOUNT"/>
        <result property="importNum" column="IMPORT_NUM"/>
        <result property="crequest" column="CREQUEST"/>
        <result property="customName" column="CUSTOM_NAME"/>
        <result property="deliveryPeriod" column="DELIVERY_PERIOD"/>
        <result property="shipTime" column="SHIP_TIME"/>
        <result property="tradeTerms" column="TRADE_TERMS"/>
        <result property="remark" column="REMARK"/>
        <result property="printStyle" column="PRINT_STYLE"/>
        <result property="oldState" column="OLD_STATE"/>
        <result property="state" column="STATE"/>
        <result property="outState" column="OUT_STATE"/>
        
        <result property="createBy" column="CREATE_BY"/>
        <result property="createDept" column="CREATE_DEPT"/>
        <result property="createTime" column="CREATE_TIME"/>
    </resultMap>
    
    <!--合同vo對象,繼承po對象屬性,下面不用在寫  -->
<resultMap type="cn.itcast.jk.vo.ContractVO" id="contractVORM" extends="contractRM">
    <!-- 合同和貨物一對多 -->
    <collection property="contractProducts" ofType="cn.itcast.jk.vo.ContractProductVO">
        <id property="id" column="CONTRACT_PRODUCT_ID"/>
        <result property="productNo" column="PRODUCT_NO"/>
        <result property="productImage" column="PRODUCT_IMAGE"/>
        <result property="productDesc" column="PRODUCT_DESC"/>
        <result property="cnumber" column="CNUMBER"/>
        <result property="outNumber" column="OUT_NUMBER"/>
        <result property="loadingRate" column="LOADING_RATE"/>
        <result property="boxNum" column="BOX_NUM"/>
        <result property="packingUnit" column="PACKING_UNIT"/>
        <result property="price" column="PRICE"/>
        <result property="amount" column="AMOUNT"/>
        <result property="finished" column="FINISHED"/>
        <result property="exts" column="EXTS"/>
        <result property="orderNo" column="ORDER_NO"/>
        
        <!--貨物與廠家多對一  -->
        <association property="factory" javaType="cn.itcast.jk.domain.Factory">
           <!-- 主鍵 -->
            <id property="id" column="FACTORY_ID"/>
            <!-- 通常屬性 -->
            <result property="fullName" column="FULL_NAME"/>
            <result property="factoryName" column="FACTORY_NAME"/>
            <result property="contacts" column="CONTACTS"/>
        </association>
        
        <!--貨物與[附件]一對多  -->
        <collection property="extCproducts" ofType="cn.itcast.jk.vo.ExtCproductVO">
            <id property="id" column="EXT_CPRODUCT_ID"/>
            <result property="ctype" column="CTYPE"/>
            <result property="productNo" column="EXT_PRODUCT_NO"/>
            <result property="productImage" column="EXT_PRODUCT_IMAGE"/>
            <result property="productDesc" column="EXT_PRODUCT_DESC"/>
            <result property="cnumber" column="EXT_CNUMBER"/>
            <result property="packingUnit" column="EXT_PACKING_UNIT"/>
            <result property="price" column="EXT_PRICE"/>
            <result property="amount" column="EXT_AMOUNT"/>
            <result property="productRequest" column="PRODUCT_REQUEST"/>
            <result property="orderNo" column="EXT_ORDER_NO"/>
            
            <!--附件與廠家多對一  -->
                <association property="factory" javaType="cn.itcast.jk.domain.Factory">
                    <!-- 主鍵 -->
                    <id property="id" column="EXT_FACTORY_ID"/>
                    <!-- 通常屬性 -->
                    <result property="fullName" column="EXT_FULL_NAME"/>
                    <result property="factoryName" column="EXT_FACTORY_NAME"/>
                    <result property="contacts" column="EXT_CONTACTS"/>
            </association>
        </collection>
    </collection>
</resultMap>
    
    
    
    <!-- 查詢 冗餘計算某個合同下的貨物/附件數量 和總金額-->
    <select id="find" parameterType="map" resultMap="contractRM">
        <!-- select * from contract_c
        where 1=1 -->
        select (select count(contract_product_id) from contract_product_c where contract_id in c.contract_id)as cpnumber,(select count(ext_cproduct_id) from ext_cproduct_c where contract_product_id in (select contract_product_id from contract_product_c where contract_id in c.contract_id)) as extnumber,
      (nvl((select sum(cnumber*price) as cptotal from contract_product_c
      where contract_id =c.contract_id),0)
      +
      nvl((select sum(cnumber*price) as exttotal from ext_cproduct_c
       where contract_product_id in (select contract_product_id from contract_product_c where contract_id=c.contract_id))
       ,0)) as total_amount,
      c.CONTRACT_ID,c.OFFEROR,c.CONTRACT_NO,c.SIGNING_DATE,c.INPUT_BY,c.CHECK_BY,c.INSPECTOR,c.IMPORT_NUM,c.CREQUEST,c.CUSTOM_NAME,c.DELIVERY_PERIOD,c.SHIP_TIME,c.TRADE_TERMS,c.REMARK,c.PRINT_STYLE,c.OLD_STATE,c.STATE,c.OUT_STATE
        from contract_c c
        where 1=1
        <if test="state!= null">and STATE=#{state}</if>
    </select>
    
    <!-- 查詢一個 -->
    <select id="get" parameterType="string" resultMap="contractRM">
        select * from contract_c
        where contract_id=#{pid, jdbcType=VARCHAR}
    </select>
    
    
    <!--查詢顯示某個合同下相關聯的貨物、附件以及廠家信息  -->
    <select id="view" parameterType="string" resultMap="contractVORM">
      select
       c.contract_id,c.offeror,c.contract_no,c.signing_date,c.input_by,c.check_by,c.inspector,c.total_amount,c.import_num,c.crequest,c.custom_name,c.delivery_period,c.ship_time,c.trade_terms,c.remark,c.print_style,c.old_state,c.state,c.out_state,c.create_by,c.create_dept,c.create_time,
       
       t.contract_product_id,
        t.product_no,t.product_image,t.product_desc,t.cnumber,t.out_number,t.loading_rate,t.box_num,t.packing_unit,t.price,t.amount,t.finished,t.exts,t.order_no,
        t.factory_id,t.full_name,t.factory_name,t.contacts,t.phone,
              
        t.ext_cproduct_id,
        t.ctype,t.ext_product_no,t.ext_product_image,t.ext_product_desc,t.ext_cnumber,t.ext_packing_unit,t.ext_price,t.ext_amount,t.product_request,
        t.ext_order_no,
        t.ext_factory_id,t.ext_full_name,t.ext_factory_name,t.ext_contacts,t.ext_phone

from
(
      select 
          contract_id,offeror,contract_no,signing_date,input_by,check_by,inspector,total_amount,import_num,crequest,custom_name,delivery_period,ship_time,trade_terms,remark,print_style,old_state,state,out_state,create_by,create_dept,create_time
       from contract_c 
) c
left join
(
       select
              cp.contract_product_id,cp.contract_id,
              cp.product_no,cp.product_image,cp.product_desc,cp.cnumber,cp.out_number,cp.loading_rate,cp.box_num,cp.packing_unit,cp.price,cp.amount,cp.finished,cp.exts,cp.order_no,
              cp.factory_id,cp.full_name,cp.factory_name,cp.contacts,cp.phone,
              
              ext.ext_cproduct_id,
              ext.ctype,ext.product_no as ext_product_no,ext.product_image as ext_product_image,ext.product_desc as ext_product_desc,
              ext.cnumber as ext_cnumber,ext.packing_unit as ext_packing_unit,ext.price as ext_price,ext.amount as ext_amount,
              ext.product_request,ext.order_no as ext_order_no,
              ext.factory_id as ext_factory_id,ext.full_name as ext_full_name,ext.factory_name as ext_factory_name,ext.contacts as ext_contacts,ext.phone as ext_phone
              
        from
        (
            select
              cp.contract_product_id,cp.contract_id,
              cp.product_no,cp.product_image,cp.product_desc,cp.cnumber,cp.out_number,cp.loading_rate,cp.box_num,cp.packing_unit,cp.price,cp.amount,cp.finished,cp.exts,cp.order_no,
              f.factory_id,f.full_name,f.factory_name,f.contacts,f.phone
            from
            (select 
            contract_product_id,contract_id,factory_id,
            product_no,product_image,product_desc,cnumber,out_number,loading_rate,box_num,packing_unit,price,amount,finished,exts,order_no
             from contract_product_c) cp
            left join 
            (select factory_id,full_name,factory_name,contacts,phone from factory_c) f
            on cp.factory_id=f.factory_id
        ) cp
        left join
        (
            select
              ext.ext_cproduct_id,ext.contract_product_id,
              ext.ctype,ext.product_no,ext.product_image,ext.product_desc,ext.cnumber,ext.packing_unit,ext.price,ext.amount,ext.product_request,ext.order_no,
              f.factory_id,f.full_name,f.factory_name,f.contacts,f.phone
            from
            (
            select 
                ext_cproduct_id,contract_product_id,factory_id,
                ctype,product_no,product_image,product_desc,cnumber,packing_unit,price,amount,product_request,order_no
             from ext_cproduct_c 
            ) ext
            left join 
            (select factory_id,full_name,factory_name,contacts,phone from factory_c) f
            on ext.factory_id=f.factory_id
        ) ext
        on cp.contract_product_id=ext.contract_product_id
) t
on c.contract_id=t.contract_id

where c.contract_id=#{contractId}
    
    </select>
    
    
    
    <!-- 新增  oracle jdbc驅動 當這個值爲null時,必須告訴它當前字段默認值的類型jdbcType=VARCHAR (mybatis定義),
            無效的列類型: 1111; nested exception is java.sql.SQLException
             mysql不用寫  -->
    <insert id="insert" parameterType="cn.itcast.jk.domain.Contract">
        insert into contract_c
        (CONTRACT_ID,OFFEROR,CONTRACT_NO,SIGNING_DATE,INPUT_BY,CHECK_BY,INSPECTOR,TOTAL_AMOUNT,
            IMPORT_NUM,CREQUEST,CUSTOM_NAME,DELIVERY_PERIOD,SHIP_TIME,TRADE_TERMS,REMARK,PRINT_STYLE,OLD_STATE,STATE,OUT_STATE,
            CREATE_BY,CREATE_DEPT,CREATE_TIME)
        values
        (
            #{id},
            #{offeror, jdbcType=VARCHAR},
            #{contractNo, jdbcType=VARCHAR},
            #{signingDate, jdbcType=TIMESTAMP},
            #{inputBy, jdbcType=VARCHAR},
            #{checkBy, jdbcType=VARCHAR},
            #{inspector, jdbcType=VARCHAR},
            #{totalAmount, jdbcType=DOUBLE},
            #{importNum, jdbcType=INTEGER},
            #{crequest, jdbcType=VARCHAR},
            #{customName, jdbcType=VARCHAR},
            #{deliveryPeriod, jdbcType=TIMESTAMP},
            #{shipTime, jdbcType=TIMESTAMP},
            #{tradeTerms, jdbcType=VARCHAR},
            #{remark, jdbcType=VARCHAR},
            #{printStyle, jdbcType=CHAR},
            #{oldState, jdbcType=INTEGER},
            #{state, jdbcType=INTEGER},
            #{outState, jdbcType=INTEGER},
            #{createBy, jdbcType=VARCHAR},
            #{createDept, jdbcType=VARCHAR},
            #{createTime, jdbcType=TIMESTAMP}
        )
    </insert>
    
    <!-- 修改 動態SQL語句 -->
    <update id="update" parameterType="cn.itcast.jk.domain.Contract">
        update contract_c
        <set>
            <if test="offeror != null">OFFEROR=#{offeror},</if>
            <if test="contractNo != null">CONTRACT_NO=#{contractNo},</if>
            <if test="signingDate != null">SIGNING_DATE=#{signingDate},</if>
            <if test="inputBy != null">INPUT_BY=#{inputBy},</if>
            <if test="checkBy != null">CHECK_BY=#{checkBy},</if>
            <if test="inspector != null">INSPECTOR=#{inspector},</if>
            <if test="totalAmount != null">TOTAL_AMOUNT=#{totalAmount},</if>
            <if test="importNum != null">IMPORT_NUM=#{importNum},</if>
            <if test="crequest != null">CREQUEST=#{crequest},</if>
            <if test="customName != null">CUSTOM_NAME=#{customName},</if>
            <if test="deliveryPeriod != null">DELIVERY_PERIOD=#{deliveryPeriod},</if>
            <if test="shipTime != null">SHIP_TIME=#{shipTime},</if>
            <if test="tradeTerms != null">TRADE_TERMS=#{tradeTerms},</if>
            <if test="remark != null">REMARK=#{remark},</if>
            <if test="printStyle != null">PRINT_STYLE=#{printStyle},</if>
            <if test="oldState != null">OLD_STATE=#{oldState},</if>
            <if test="state != null">STATE=#{state},</if>
            <if test="outState != null">OUT_STATE=#{outState},</if>
        </set>
        where contract_id=#{id}
    </update>
    
    <!-- 刪除一條 -->
    <delete id="deleteById" parameterType="string">
        delete from contract_c
        where contract_id=#{pid}
    </delete>
    
    <!-- 刪除多條(一維字符串數組) -->
    <delete id="delete" parameterType="string">
        delete from contract_c
        where contract_id in
        <foreach collection="array" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </delete>
    
    <!-- 修改狀態 0草稿  1上報-->
    <update id="updateState" parameterType="map">
        update contract_c set state=#{state}
        where contract_id in
        <foreach collection="ids" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </update>

</mapper>

 

 

 

 字符數組工具類算法

 

package cn.itcast.util;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.text.DecimalFormat;

import java.net.URLEncoder;
import java.net.URLDecoder;
import java.util.Date;


/** UtilFuns is a JavaBean.  */
 public class UtilFuns {


  static public String newLine(){
      return System.getProperty("line.separator"); 
  }
  

    /* 驗證數組是否爲空 */
    public static boolean arrayValid(Object[] objects) {
        if (objects != null && objects.length > 0) {
            return true;
        } else {
            return false;
        }
    }

    /* 驗證list是否爲空 */
    public boolean listValid(List list) {
        if (list != null && list.size() > 0) {
            return true;
        } else {
            return false;
        }
    }
  

  //得到年齡
  public int age(String dateStart, String dateEnd) throws Exception{
      int yearStart = Integer.parseInt(dateStart.substring(0,4));
      int yearEnd = Integer.parseInt(dateEnd.substring(0,4));
      return yearEnd-yearStart;
  }
  
  //是否爲奇數
  public boolean isOdd(int i){
      if(i%2==0){
          return false;
      }else{
          return true;
      }
  }

  public String cutStr(String str,int len){
      try{
          str = str.substring(0,len);
      }catch(Exception e){
          return str;
      }
      return str;
  }
  
  //返回固定長度串,空白地方用空格填充 by tony 20110926
  public String fixSpaceStr(String str,int len){
      StringBuffer sBuf = new StringBuffer();
      try{
          if(str.length()>len){
              return str;
          }else{
              sBuf.append(str);
              for(int i=0;i<(len-str.length());i++){
                  sBuf.append(" ");
              }
              return sBuf.toString();
          }
      }catch(Exception e){
          return str;
      }
  }
  
  public String fixSpaceStr(int number,int len){
      return fixSpaceStr(String.valueOf(number),len);
  }
  
  //前綴空格
  public String prefixSpaceStr(String str,int len){
      StringBuffer sBuf = new StringBuffer();
      try{
          if(str.length()>len){
              return str;
          }else{
              for(int i=0;i<(len-str.length());i++){
                  sBuf.append(" ");
              }
              sBuf.append(str);
              return sBuf.toString();
          }
      }catch(Exception e){
          return str;
      }
  }
  
  //截取字符,若是超過長度,截取並加省略號 by tony 20101108
  public String suspensionStr(String str,int len){
      try{
          str = str.substring(0,len) + "...";
      }catch(Exception e){
          return str;
      }
      return str;
  }

  //url get方式傳遞參數 by tony 20110328
  public static String joinUrlParameter(List<String> sList){
      StringBuffer sBuf = new StringBuffer();
      for(Iterator it = sList.iterator(); it.hasNext();){
          sBuf.append("&").append(it.next()).append("=").append(it.next());
      }
      return sBuf.substring(1, sBuf.length());    //去掉第一個&符號
  }
  
  /** SplitStr 功能:返回分割後的數組
   * <br>輸入參數:String str 設置返回系統時間樣式
   * <br>輸入參數:String SplitFlag 設置分割字符
   * <br>輸出參數:string[] 返回分割後的數組
   * <br>做者:陳子樞
   * <br>時間:2003-9-7
   * <br>用法:
   */
/*
      String s[] = SplitStr("asd asd we sd"," ");
      for (int i=0;i<s.length;i++){
        System.out.println(s[i]);
      }
*/
  static public String[] splitStr(String str,String SplitFlag){
    int i =0;
    try{
      StringTokenizer st = new StringTokenizer(str, SplitFlag);
      String tokens[] = new String[st.countTokens()];
      //System.out.println(st.countTokens());
      while (st.hasMoreElements()) {
        tokens[i] = st.nextToken();
        //System.out.println(tokens[i]);
        i++;
      }
      return tokens;
    }catch(Exception e){
      return null;
    }
  }
  
  //相似google那樣實現多個關鍵字的查詢,關鍵字之間用空格或逗號隔開 by tony 20110523
  //支持的分隔符 英文逗號,中文逗號,空格
  public String[] splitFindStr(String str){
    if(str==null){
        return null;
    }
    String[] aStr = null;
    str = str.replaceAll(",", " ");        //英文逗號
    str = str.replaceAll("", " ");        //中文逗號
    aStr = this.splitStr(str, " ");        //空格  
    return aStr;
 }
 
  /* 階梯函數,例如,a,b,c 返回 a;a,b;a,b,c by tony 20110330 */
  static public String[] splitStair(String str,String SplitFlag){
      try{
          String[] _temp = splitStr(str, SplitFlag);
          for(int i=1;i<_temp.length;i++){
              _temp[i] = _temp[i-1]+SplitFlag+_temp[i];
          }
          return _temp;
      }catch(Exception e){
          return null;
      }
  }

  /** SplitStr 功能:將數組合併爲一個字符串
   * <br>輸入參數:String aStr 要合併數組
   * <br>輸入參數:String SplitFlag 設置分割字符
   * <br>輸出參數:String 要合併數組
   * <br>做者:陳子樞
   * <br>時間:2004-1-9
   * <br>用法:
   */


  static public String joinStr(String[] aStr,String SplitFlag){
    StringBuffer sBuffer = new StringBuffer();
    if (aStr != null){
      for (int i=0;i<aStr.length;i++){
        sBuffer.append(aStr[i]).append(SplitFlag);
      }
      sBuffer.delete(sBuffer.length() - 1, sBuffer.length()); //去掉最後的分隔符 SplitFlag
    }else{
      sBuffer = sBuffer.append("");
    }
    return sBuffer.toString();
  }

  /* 連接,但中間無連接符號 add by tony 20100322 */
  static public String joinStr(String[] aStr){
    StringBuffer sBuffer = new StringBuffer();
    if (aStr != null){
      for (int i=0;i<aStr.length;i++){
        sBuffer.append(aStr[i]);
      }
    }else{
      sBuffer = sBuffer.append("");
    }
    return sBuffer.toString();
  }
  
  /** JoinStr 
   * <br>功能:將數組合併爲一個字符串
   * <br>輸入參數:String sPrefix 數組元素加的前綴
   * <br>輸入參數:String sSuffix 數組元素加的後綴
   * <br>輸入參數:String SplitFlag 設置分割字符
   * <br>輸出參數:String 合併後的字符串
   * <br>做者:陳子樞
   * <br>時間:2005-3-17
   * <br>用法:
   */


  static public String joinStr(String[] aStr,String sPrefix,String sSuffix,String SplitFlag){
    StringBuffer sBuffer = new StringBuffer();
    if (aStr != null){
      for (int i=0;i<aStr.length;i++){
        sBuffer.append(sPrefix).append(aStr[i]).append(sSuffix).append(SplitFlag);
      }
      sBuffer.delete(sBuffer.length() - SplitFlag.length(), sBuffer.length()); //去掉最後的分隔符 SplitFlag
    }else{
      sBuffer = sBuffer.append("");
    }
    return sBuffer.toString();
  }
  
  /* 返回用於in查詢的串  'x','y' */
  static public String joinInStr(String[] aStr){
      StringBuffer sBuffer = new StringBuffer();
      if (aStr != null){
          for (int i=0;i<aStr.length;i++){
              sBuffer.append("'").append(aStr[i]).append("'").append(",");
          }
          sBuffer.delete(sBuffer.length() - 1, sBuffer.length());
      }else{
          sBuffer = sBuffer.append("");
      }
      return sBuffer.toString();
  }

  /* 連接,但中間無連接符號 add by tony 20100322 */
  static public String joinStr(String[] aStr,String sPrefix,String sSuffix){
    StringBuffer sBuffer = new StringBuffer();
    if (aStr != null){
      for (int i=0;i<aStr.length;i++){
        sBuffer.append(sPrefix).append(aStr[i]).append(sSuffix);
      }
    }else{
      sBuffer = sBuffer.append("");
    }
    return sBuffer.toString();
  }

  /* 連接len(s)個symbol符號 add by tony 20100407 */
  static public String joinStr(String s, String symbol){
      StringBuffer sBuf = new StringBuffer();
      for (int i=0;i<s.length();i++){
          sBuf.append(symbol);
      }
      return sBuf.toString();
  }
  
  static public String joinStr(int len, String symbol){
      StringBuffer sBuf = new StringBuffer();
      for (int i=0;i<len;i++){
          sBuf.append(symbol);
      }
      return sBuf.toString();
  }  
  
  /** SysTime 功能:返回系統時間
 * <br>輸入參數:int style 設置返回系統時間樣式
 * <br>輸出參數:string 返回系統時間樣式
 * <br>做者:陳子樞
 * <br>時間:2003-6-24
 * <br>存在問題:中文亂碼,但JSP中顯示正常。
 */
  static public String SysTime(String strStyle){
    String s = "";
    if (strStyle.compareTo("")==0){
        strStyle = "yyyy-MM-dd HH:mm:ss";    //default
    }
    java.util.Date date=new java.util.Date();
    SimpleDateFormat dformat=new SimpleDateFormat(strStyle);
    s = dformat.format(date);
    return s;
  }

  static public String sysTime(){
    String s = "";
    java.util.Date date=new java.util.Date();
    SimpleDateFormat dformat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    s = dformat.format(date);
    return s;
  }

  static public String sysDate(){
    String s = "";
    java.util.Date date=new java.util.Date();
    SimpleDateFormat dformat=new SimpleDateFormat("yyyy-MM-dd");
    s = dformat.format(date);
    return s;
  }


  /* add by tony 20091113 */
  public static boolean isNull(Object obj){
    try{
      if(obj==null){
          return true;
      }
      return false;
    }catch(Exception e){
      return false;
    }
  }
  
  public static boolean isNotNull(Object obj){
    try{
      if(obj==null){
          return false;
      }
      return true;
    }catch(Exception e){
      return true;
    }
  }  

  public static boolean isEmpty(String str){
    try{
      if(str==null || str.equals("null") || str.equals("")){
          return true;
      }
      return false;
    }catch(Exception e){
      return false;
    }
  }
  
  public static boolean isEmpty(String strs[]){
      try{
          if(strs==null || strs.length<=0){
              return true;
          }
          return false;
      }catch(Exception e){
          return false;
      }
  }

  public static boolean isNotEmpty(String str){
    try{
      if(str==null || str.equals("null") || str.equals("")){
          return false;
      }
      return true;
    }catch(Exception e){
      return true;
    }
  }

  public static boolean isNotEmpty(Object obj){
    try{
      if(obj==null || obj.toString().equals("null") || obj.toString().equals("")){
          return false;
      }
      return true;
    }catch(Exception e){
      return true;
    }
  }
  
  public static boolean isNotEmpty(List obj){
      try{
          if(obj==null || obj.size()<=0){
              return false;
          }
          return true;
      }catch(Exception e){
          return true;
      }
  }
  
  /** 功能:用於轉換爲null的字段。
   * <br>入參:String strvalue 設置要轉換的字符串
   * <br>出參:不爲「null」的返回原串;爲「null」返回""。
   * <br>做者:陳子樞
   * <br>時間:2003-9-16
   * <p>用法:optionFuns.convertNull(String.valueOf(oi.next()))</p>
   */
  public static String convertNull(String strvalue)
  {
    try{
      if(strvalue.equals("null") || strvalue.length()==0){
        return "";
      }else{
        return strvalue.trim();
      }
    }catch(Exception e){
      return "";
    }
  }

  public static String[] convertNull(String[] aContent)
  {
    try{
      for(int i=0;i<aContent.length;i++){
        if(aContent[i].toLowerCase().compareTo("null")==0){
          aContent[i] = "";
        }
      }
      return aContent;
    }catch(Exception e){
      return null;
    }
  }
    
  public static String convertNull(Object o)
  {
    try{
      String strvalue = String.valueOf(o);
      if(strvalue.equals(null) || strvalue.equals("null") || strvalue.length()==0){
        return "";
      }else{
        return strvalue.trim();
      }
    }catch(Exception e){
      return "";
    }
  }
  
  //將爲null的數據轉爲0,用在數值的值從數據庫中讀出的狀況
  public static int ConvertZero(Object o)
  {
    try{
      String s = convertNull(o);
      if(s==""){
        return 0;
      }else{
        return Integer.parseInt(s);
      }
    }catch(Exception e){
      return 0;
    }
  }
  
  //將爲null的數據轉爲0,用在數值的值從數據庫中讀出的狀況
  public static int cvtPecrent(Object o)
  {
    try{
      String s = convertNull(o);
      if(s==""){
        return 0;
      }else{
        return Integer.parseInt(s);
      }
    }catch(Exception e){
      return 0;
    }
  }  
  
  //if 0 then return "";
  public static String FormatZero(Object o)
  {
    try{
      String s = convertNull(o);
      if(s.compareTo("")==0){
        return "";
      }else if(s.compareTo("0.0")==0){ 
        return "";
    }else{
        return String.valueOf(s);
      }
    }catch(Exception e){
      return "";
    }
  }
  
  //if 0 then return "";
  public static String FormatZero(String s)
  {
    try{
      if(s.compareTo("0")==0){
        return "";
      }else{
        return s;
      }
    }catch(Exception e){
      return "";
    }
  }
  
  //patter="####.000"
  public static String FormatNumber(Object o,String patter)
  {
      double d = 0;
    try {
      d = Double.parseDouble(String.valueOf(o));
      DecimalFormat df = new DecimalFormat(patter);
      return df.format(d);
    }
    catch (Exception e) {
        System.out.println(e.getMessage());
           return "";
    }
  }

  
  //patter="####.00"
  public static String FormatNumber(String s)
  {
      double d = 0;
    try {
      d = Double.parseDouble(s);
      DecimalFormat df = new DecimalFormat(",###.00");
      return df.format(d);
    }
    catch (Exception e) {
        System.out.println(e.getMessage());
        return "";
    }
  }
  
  //只用在表格的輸出
  public static String ConvertTD(String strvalue)
  {
    try{
      strvalue = strvalue.trim();
      if(strvalue.equals("null") || strvalue.length()==0){
        return "&nbsp;";
      }else{
        return strvalue;
      }
    }catch(Exception e){
      return "&nbsp;";
    }
  }

  public static String ConvertSpaceTD(Object o)
  {
    try{
      String strvalue = String.valueOf(o);
      strvalue = strvalue.trim();
      if(strvalue.equals("null") || strvalue.length()==0){
        return "&nbsp;";
      }else{
        return " " + strvalue.trim();
      }
    }catch(Exception e){
      return "&nbsp;";
    }
  }
  
  /*
    只轉中文,不處理null
    讀取記錄時去掉數據兩邊的空格;而錄入數據時,維持用戶的輸入,哪怕用戶多輸入了空格
    緣由在於有時可能用戶有意輸入空格。例如:備註字段原來有內容,如今用戶想清空。
  */
  public static String ConvertCH(String strvalue)
  {
    System.out.println("ConvertCH:"+strvalue);
    try{
      if(strvalue==null){
        return "null";
      }else if(strvalue.length()==0){
        return "";      
      }else{
        strvalue = new String(strvalue.getBytes("ISO8859_1"), "GB2312");
        return strvalue;
      }
    }catch(Exception e){
      return "";
    }
  }
  
  public static String ConvertCStr(String strvalue)
  {
    try{
      strvalue = convertNull(strvalue);
      if(strvalue.equals("")){
        return "";
      }else{
        strvalue = new String(strvalue.getBytes("ISO8859_1"), "GB2312");
        return strvalue;
      }
    }catch(Exception e){
      return "";
    }
  }

  public static String ConvertCStr(Object o)
  {
    String strvalue = "";
    try{
      strvalue = String.valueOf(o);
      strvalue = convertNull(strvalue);
      if(strvalue.equals("")){
        return "";
      }else{
        strvalue = new String(strvalue.getBytes("ISO8859_1"), "GB2312");
        return strvalue;
      }
    }catch(Exception e){
      System.out.println("ConvertCStr:" + e.toString());
      return "";
    }
  }
  
  /**
   *UrlEncoder 進行URL編碼
   */
    public String UrlEncoder(String s)
    {
        String s1 = "";
        if(s == null)
            return "";
        try
        {
            s1 = URLEncoder.encode(s);
        }
        catch(Exception e)
        {
            System.out.println("URL Encoder :" + e.toString());
            s1 = "";
        }
        return s1;
    }

  /**
   *URLDecoder 進行URL解碼
   */
    public String UrlDecoder(String s)
    {
        String s1 = "";
        if(s == null)
            return "";
        try
        {
            s1 = URLDecoder.decode(s);
        }
        catch(Exception e)
        {
            System.out.println("URL Encoder :" + e.toString());
            s1 = "";
        }
        return s1;
    }
    
  /**
   * 將字符串轉化成首字母大寫,其他字母小寫的格式
   * @param source 傳入字符串
   * @return String
   */
  public static String format_Aaa(String source) {

    if (source==null) return null;
    if (source.equals("")) return "";

    String a;
    a = source.substring(0, 1);
    a = a.toUpperCase();
    return a + source.substring(1);

  }
  
  /**
   * 將字符串轉換成Long型
   * @param param 傳入字符串
   * @return 長整形
   */
  public static long parseLong(String param) {
    long l=0;
    try {
      l = Long.parseLong(param);
    }
    catch (Exception e) {
    }

    return l;
  }

  /**
   * 將字符串轉換成Float型
   * @param param 傳入字符串
   * @return 浮點型
   */
  public static float parseFloat(String param) {
    float l=0;
    try {
      l = Float.parseFloat(param);
    }
    catch (Exception e) {
    }

    return l;
  }

  /**
   * 將字符串轉換成Integer型
   * @param param 傳入字符串
   * @return 整形
   */
  public static int parseInt(String param) {
    int l=0;
    try {
      l = Integer.parseInt(param);
    }
    catch (Exception e) {
    }

    return l;
  }


    public static Date parseDate(String currDate, String format) {
        SimpleDateFormat dtFormatdB = null;
        try {
            dtFormatdB = new SimpleDateFormat(format);
            return dtFormatdB.parse(currDate);
        }catch (Exception e){
            dtFormatdB = new SimpleDateFormat("yyyy-MM-dd");
            try {
                return dtFormatdB.parse(currDate);
            }catch (Exception ex){}
        }
        return null;
    }

    public static Date parseDate(String currDate) {
        SimpleDateFormat dtFormatdB = null;
        dtFormatdB = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return dtFormatdB.parse(currDate);
        }catch (Exception e){
            try {
                return dtFormatdB.parse(currDate);
            }catch (Exception ex){}
        }
        return null;
    }
    
    public static Date parseTime(String currDate, String format) {
        SimpleDateFormat dtFormatdB = null;
        try {
            dtFormatdB = new SimpleDateFormat(format);
            return dtFormatdB.parse(currDate);
        }catch (Exception e){
            dtFormatdB = new SimpleDateFormat("HH:mm:ss");
            try {
                return dtFormatdB.parse(currDate);
            }catch (Exception ex){}
        }
        return null;
    }

    public static Date parseDateTime(String currDate, String format) {
        SimpleDateFormat dtFormatdB = null;
        try {
            dtFormatdB = new SimpleDateFormat(format);
            return dtFormatdB.parse(currDate);
        }catch (Exception e){
            dtFormatdB = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                return dtFormatdB.parse(currDate);
            }catch (Exception ex){}
        }
        return null;
    }
    
  /**
   * 將字符串轉換成Double型
   * @param param 傳入字符串
   * @return double型
   */
  public static double parseDouble(String param) {
    double l=0;
    try {
      l = Double.parseDouble(param);
    }
    catch (Exception e) {
    }

    return l;
  }

  /**
   * s是否存在ArrayList中,存在返回數組下標,不存在返回-1
   */
  public static int existElements(String s,ArrayList aList) {
    try{
      for (int i = 0; i < aList.size(); i ++) {
        if (s.equals(aList.get(i))){
          return i;
        }
      }
    }catch(Exception e){   }
    return -1;
  }

  /**
   * s是否存在String數組中,存在返回數組下標,不存在返回-1
   */
  public static int existElements(String s,String[] a) {
    try{
      for (int i = 0; i < a.length; i ++) {
        if (s.compareTo((a[i].trim()))==0){  
          return i;
        }
      }
    }catch(Exception e){   }
    return -1;
  }
  
  /**
   * 判斷對象o是否存在於set對象集合中 create by tony 20090611
   */  
  public static boolean existElements(Object o, Set set) {
      boolean isExists = false;
      Iterator it = set.iterator();
      while(it.hasNext())
      {
           Object obj = it.next();
           if(o.equals(obj))
           {
               isExists=true;
               break;
           }
      }
      return isExists;
  }

  /**
   * s是否存在ArrayList中,存在返回數組下標,不存在返回-1
   */
  public static int IsIndexOfElements(String s,ArrayList aList) {
    try{
      String s1 = "";
      for (int i = 0; i < aList.size(); i ++) {
        s1 = String.valueOf(aList.get(i));
        if (s1.indexOf(s)!=-1){
          return i;
        }
      }
    }catch(Exception e){   }
    return -1;
  }
  
  /**
   * 將ArrayList轉換爲一維String數組,並把其中的null換成空字符串
   * @param aList 傳入的Arraylist
   */
  public String[] ArrayListToString(ArrayList aList) {
    String[] s = new String[aList.size()];
    for (int i = 0; i < aList.size(); i ++) {
      s[i] = this.convertNull(aList.get(i));
    }
    return s;
  }
  
  
  /**
   * 將數組中的null換成空字符串
   * @param al 傳入的Arraylist,同時也是輸出結果
   */
  public static void formatArrayList(ArrayList al) {

    for (int i = 0; i < al.size(); i ++) {
      if (al.get(i) == null)
        al.set(i, "");
    }

  }

    /** ComboList 功能:選定在下拉列表框中與查找到數據,相符的那一項內容
     * <br>輸入參數:String CurrentValue 查找出的數據庫中的數據
     *               String[] content 須要輸出的全部下拉列表框的內容
     * <br>輸出參數:返回下拉列表
      * <br>注意事項:values爲0開始,並且中間不能斷開
     */
    public String ComboList(String CurrentValue, String[] content) {
      int i = 0;
      StringBuffer sBuf = new StringBuffer();
      String selected = " selected";
      try{
        sBuf.append("<option value='' selected>--請選擇--</option>");
        for (i = 0; i < content.length; i++) {
          sBuf.append("\n<option value='").append(i).append("'");
          if (CurrentValue.compareTo(String.valueOf(i)) == 0) {
            sBuf.append(selected);
          }
          sBuf.append(">").append(content[i]).append("</option>");
        }
        return sBuf.toString();
      }catch(Exception e){
        return "";
      }
    }

    public String ComboListMust(String CurrentValue, String[] content) {
      int i = 0;
      StringBuffer sBuf = new StringBuffer();
      String selected = " selected";
      try{
        for (i = 0; i < content.length; i++) {
          sBuf.append("\n<option value='").append(i).append("'");
          if (CurrentValue.compareTo(String.valueOf(i)) == 0) {
            sBuf.append(selected);
          }
          sBuf.append(">").append(content[i]).append("</option>");
        }
        return sBuf.toString();
      }catch(Exception e){
        return "";
      }
    }
    
    /** ComboList 功能:選定在下拉列表框中與查找到數據,相符的那一項內容
     * <br>輸入參數:String CurrentValue 查找出的數據庫中的數據
     *               String[] values  須要輸出的全部下拉列表框的內容所對應的值
     *               String[] content 須要輸出的全部下拉列表框的內容
     * <br>輸出參數:返回下拉列表
     * <br>修改:陳子樞
     * <br>修改時間:2003-9-4
     * <br>注意事項:values和content數組個數必須相同.適合從數據庫中取值
    <%
      String[] aContextOPERATE_TYPE = {"定檢","輪換","抽檢"};
      out.print(optionFuns.ComboList("",aContextOPERATE_TYPE,aContextOPERATE_TYPE));
    %>
     */
    public String ComboList(String CurrentValue,String[] values, String[] content) {
      int i = 0;
      StringBuffer sBuf = new StringBuffer();
      String selected = " selected";

      try{
        if(CurrentValue==null){
            CurrentValue = "";
        }
        sBuf.append("<option value='' selected>--請選擇--</option>");
        for (i = 0; i < content.length; i++) {
          sBuf.append("<option value='").append(values[i]).append("'");
          if (CurrentValue.compareTo(values[i]) == 0) {
            sBuf.append(selected);
          }
          sBuf.append(">").append(content[i]).append("</option>");
        }
        return sBuf.toString();
      }catch(Exception e){
        return "";
      }
    }

    public String ComboListMust(String CurrentValue,String[] values, String[] content) {
      int i = 0;
      StringBuffer sBuf = new StringBuffer();
      String selected = " selected";

      try{
        for (i = 0; i < content.length; i++) {
          sBuf.append("<option value='").append(values[i]).append("'");
          if (CurrentValue.compareTo(values[i]) == 0) {
            sBuf.append(selected);
          }
          sBuf.append(">").append(content[i]).append("</option>");
        }
        return sBuf.toString();
      }catch(Exception e){
        return "";
      }
    } 
    
  /** StrToTimestamp 功能:將字符串轉換爲Timestamp 。
   * <br>輸入參數:String timestampStr 設置要轉換的字符串
   *              String pattern 要轉換的format
   * <br>輸出參數:若是格式正確返回格式後的字符串。
   *              不正確返回系統日期。
   * <br>做者:陳子樞
   * <br>時間:2003-8-26
   */
  public static Timestamp StrToTimestamp(String timestampStr,String pattern) throws ParseException {
    java.util.Date date = null;
    SimpleDateFormat format = new SimpleDateFormat(pattern);
    try {
      date = format.parse(timestampStr);
    } catch (ParseException ex) {
      throw ex;
    }
    return date == null ? null : new Timestamp(date.getTime());
  }

  //ex:utilFuns.StrToDateTimeFormat("2005-12-01 00:00:00.0,"yyyy-MM-dd")
  public static String StrToDateTimeFormat(String timestampStr,String pattern) throws ParseException {
    String s ="";
    try{
      s = String.valueOf(StrToTimestamp(timestampStr, pattern));
      s = s.substring(0,pattern.length());
    }catch(Exception e){ }
    return s;
  }

  //ex:utilFuns.StrToDateTimeFormat("2005-12-01 00:00:00.0,"yyyy-MM-dd")
  public static String dateTimeFormat(Date date,String pattern) throws ParseException {
    String s ="";
    try{
        SimpleDateFormat dformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        s = dformat.format(date);
        s = String.valueOf(StrToTimestamp(s, pattern));
        s = s.substring(0,pattern.length());
    }catch(Exception e){ }
    return s;
  }
  public static String dateTimeFormat(Date date) throws ParseException {
      String s ="";
      try{
          SimpleDateFormat dformat = new SimpleDateFormat("yyyy-MM-dd");
          s = dformat.format(date);
          s = String.valueOf(StrToTimestamp(s, "yyyy-MM-dd"));
          s = s.substring(0,"yyyy-MM-dd".length());
      }catch(Exception e){ }
      return s;
  }
  
  //add by tony 20100228 轉換中文 格式必須爲:"yyyy-MM-dd HH:mm:ss"的一部分
  public static String formatDateTimeCN(String date) throws ParseException {
      String s ="";
      try{
          if(UtilFuns.isEmpty(date)){
              return "";
          }
          if(date.indexOf(".")>-1){
              date = date.substring(0, date.indexOf("."));
          }
          if(date.length()==4){            //yyyy
              s = date+"";
          }else if(date.length()==7){    //yyyy-MM
              s = date.replaceAll("-0", "-").replaceFirst("-", "")+"";
          }else if(date.length()==10){    //yyyy-MM-dd
              s = date.replaceAll("-0", "-").replaceFirst("-", "").replaceFirst("-", "")+"";
          }else if(date.length()==2){    //HH
              s = date+"";
          }else if(date.length()==5){    //HH:mm
              s = date.replaceAll(":0", ":").replaceFirst(":", "")+"";
          }else if(date.length()==8){    //HH:mm:ss
              s = date.replaceAll(":0", ":").replaceFirst(":", "").replaceFirst(":", "")+"";
          }else if(date.length()==13){    //yyyy-MM-dd HH
              s = date.replaceAll("-0", "-").replaceFirst("-", "").replaceFirst("-", "").replaceAll(" 0", " ").replaceFirst(" ", "")+"";
          }else if(date.length()==16){    //yyyy-MM-dd HH:mm
              s = date.replaceAll("-0", "-").replaceFirst("-", "").replaceFirst("-", "").replaceAll(" 0", " ").replaceFirst(" ", "").replaceAll(":0", ":").replaceFirst(":", "")+"";
          }else if(date.length()==19){    //yyyy-MM-dd HH:mm:ss
              s = date.replaceAll("-0", "-").replaceFirst("-", "").replaceFirst("-", "").replaceAll(" 0", " ").replaceFirst(" ", "").replaceAll(":0", ":").replaceFirst(":", "").replaceFirst(":", "")+"";
          }
          s = s.replaceAll("0[時分秒]", "");    //正則 0時0分0秒的都替換爲空
      }catch(Exception e){ }
      
      return s;
  }
  
  //add by tony 2011-07-26 返回英文格式日期 oct.10.2011
  public static String formatDateEN(String date) throws ParseException {
      String s ="";
      int whichMonth = 1;
      try{
          if(UtilFuns.isEmpty(date)){
              return "";
          }
          String[] aString = date.replaceAll("-0", "-").split("-");
          whichMonth = Integer.parseInt(aString[1]);
          if(whichMonth==1){
              s = "Jan";
          }else if(whichMonth==2){
              s = "Feb";
          }else if(whichMonth==3){
              s = "Mar";
          }else if(whichMonth==4){
              s = "Apr";
          }else if(whichMonth==5){
              s = "May";
          }else if(whichMonth==6){
              s = "Jun";
          }else if(whichMonth==7){
              s = "Jul";
          }else if(whichMonth==8){
              s = "Aug";
          }else if(whichMonth==9){
              s = "Sept";
          }else if(whichMonth==10){
              s = "Oct";
          }else if(whichMonth==11){
              s = "Nov";
          }else if(whichMonth==12){
              s = "Dec";
          }
          s = s+"."+aString[2]+","+aString[0];
          
      }catch(Exception e){ }
      
      return s;
  }

  //返回年月格式 2010-7
  public String formatShortMonth(String strDate){
      return strDate.substring(0,7).replaceAll("-0", "-");
  }
  
  //返回年月格式 2010-07
  public String formatMonth(String strDate){
      return strDate.substring(0,7);
  }
  
  
  
  //刪除最後1個字符
  public static String delLastChar(String s){
    try{
      if(s.length()>0){
        s = s.substring(0,s.length()-1);  
      }      
    }catch(Exception e){
      return "";
    }
    return s;
  }
  
  //刪除最後len個字符
  public static String delLastChars(String s,int len){
    try{
      if(s.length()>0){
        s = s.substring(0,s.length()-len);  
      }      
    }catch(Exception e){
      return "";
    }
    return s;
  }
  
  //替換網頁用字符-配合FCKEditor使用 .replaceAll("'","&apos;") //for viewpage
  public String htmlReplaceAll(String s){
      try{
          StringBuffer sBuf = new StringBuffer();
          //.replaceAll("\\\\","\\\\\\\\").replaceAll("&","&amp;")
          sBuf.append(s.replaceAll(" ","&nbsp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll("\"","&quot;").replaceAll("\n","<br\\>"));
          return sBuf.toString();
      }catch(Exception e){
          return "";
      }
  }
  
  //for viewpage by jstl/make html
  public static String htmlNewline(String s){
      try{
          //如不替換空格,html解釋時會自動把多個空格顯示爲一個空格,這樣當咱們經過空格來佈局時就出現textarea中和html頁面展示不一致的狀況 tony
          //s.replaceAll(" ","&nbsp;") 不能進行空格的替換,不然頁面內容中若是有<img src="xxx.jpg" \>等標籤,內容就會顯示亂;<img&nbsp;src="xxx.jpg"nbsp;\>
          return s.replaceAll(" ","&nbsp;").replaceAll("\n","<br\\>");  
      }catch(Exception e){
          return "";
      }
  }
  

  /** getPassString 功能:用於轉換爲後幾位的爲*。
   * <br>輸入參數:String strvalue 設置要轉換的字符串
   *              int Flag 位數。
   * <br>輸出參數:。
   * <br>做者:範波
   * <br>時間:2006-8-7
   * <br>存在問題:
   * <br>用法:
   *          <%=utilFuns.ConvertString("abcdef",3)%>
   */
  public static String getPassString( String strvalue, int Flag ) {
    try {
      if ( strvalue.equals("null") || strvalue.compareTo("")==0){
        return "";
      } else {
        int intStrvalue = strvalue.length();
        if ( intStrvalue > Flag ) {
          strvalue = strvalue.substring( 0, intStrvalue - Flag );

        }
        for ( int i = 0; i < Flag; i++ ) {
          strvalue = strvalue + "*";
        }

        //System.out.print( "strvalue:" + strvalue );
        return strvalue;
      }
    }
    catch (Exception e) {
      return strvalue;
    }
  }
  
 /** getPassString 功能:用於轉換爲後幾位的爲*。
 * <br>輸入參數:String strvalue 設置要轉換的字符串
 *              int Flag 起位數。
 *              int sFlag 末位數。 
 * <br>輸出參數:。
 * <br>做者:範波
 * <br>時間:2006-8-7
 * <br>存在問題:
 * <br>用法:
 *          <%=optionFuns.getPassString(String.valueOf(oi.next()),3)%>
 */
public static String getPassString( String strvalue, int Flag, int sFlag ,int iPassLen ) {
  try {
    
    if ( strvalue.equals( "null" ) ) {
      return "";
    } else {
      String strvalue1="";
      String strvalue2="";
      int intStrvalue = strvalue.length();
      if(sFlag>=Flag){
        if ( intStrvalue > Flag ) {
          strvalue1 = strvalue.substring( 0,  Flag );
          strvalue2 = strvalue.substring(  sFlag, intStrvalue );
        } else {
          strvalue1 = "";
          strvalue2 = "";
        }
        for ( int i = 0; i < iPassLen; i++ ) {
          strvalue1 = strvalue1 + "*";
        }
        strvalue=strvalue1+strvalue2;
      }
      //System.out.print( "strvalue:" + strvalue );
      return strvalue;
    }
  }
  catch (Exception e) {
    return strvalue;
  }
  } 
  
  
  /* 
    by czs 2006-8-17
    OPTION:
        取得字符串iStartPos位置到iEndPos位置,將中間這部分轉換iPatternLen個sPattern
    EXSAMPLE:
        getPatternString("CHEN ZISHU",5,7,"*",3)
        RESULT: CHEN ***SHU

        getPatternString("CHEN ZISHU",10,0,".",3)
        RESULT: CHEN******

  */
  public static String getPatternString( String s, int iStartPos, int iEndPos, String sPattern, int iPatternLen ) {
    try {
      if (iEndPos==0) {
        iEndPos = s.length();
      }
      
      String sStartStr = "";
      String sCenterStr = "";
      String sEndStr = "";
      
      if ( s.equals("null")){
        return "";
      } else {
        int ints = s.length();
        if ( ints > iStartPos ) {
          sStartStr = s.substring( 0, iStartPos );
        }else{
          return s;
        }
        if ( ints > iEndPos) {
          sEndStr = s.substring( iEndPos, ints );
        }
        for ( int i = 0; i < iPatternLen; i++ ) {
          sCenterStr = sCenterStr + sPattern;
        }
        return sStartStr + sCenterStr + sEndStr;
      }
    }
    catch (Exception e) {
      System.out.println(e);
      return s;
    }
  }

  public static String getPatternString( String s, int iStartPos, String sPattern, int iPatternLen ) {
    return getPatternString(s,iStartPos,0,sPattern,iPatternLen);
  }

  public static String getPatternString( String s, int iStartPos, String sPattern ) {
    return getPatternString(s,iStartPos,0,sPattern,3);
  }

  
    /** getQQString 功能:用於轉換爲後幾位的爲*。
* <br>輸入參數:String strvalue 設置要轉換的字符串
*               
* <br>輸出參數:。
* <br>做者:範波
* <br>時間:2006-8-7
* <br>存在問題:
* <br>用法:
*          <%=optionFuns.getQQString(String.valueOf(oi.next()))%>
*/
public static String getQQString( String strvalue ) {
    try {
      String QQ="";
      if ( strvalue.equals("") ) {
        return "";
      } else {
         QQ="<img src=\"http://wpa.qq.com/pa?p=1:"+strvalue
            +":4\">"
            +" <SPAN title=\"有事叫我!\" style=\"CURSOR: hand\""
            +" onclick=\"window.open('http://wpa.qq.com/msgrd?V=1&amp;Uin="+strvalue
            +"&amp;Site=21pan&amp;Menu=yes')\">"+strvalue+"</SPAN>";
        }
        strvalue=QQ;
        //System.out.print( "strvalue:" + strvalue );
        return strvalue;
      
    }
    
    catch (Exception e) {
      return strvalue;
    }
}

    public String getNoExistString(String allString, String existString){
        return this.getNoExistString(this.splitStr(allString, ","), existString);
    }
    
    /* 返回existString中的每一個字串不在allString中的 */
    public String getNoExistString(String[] allString, String existString){
        existString = existString + ",";
        if(allString==null&&allString.length==0){
            return "";
        }
        StringBuffer sBuf = new StringBuffer();
        for(int i=0;i<allString.length;i++){
            if(existString.indexOf(allString[i])==-1){
                sBuf.append(allString[i]).append(",");
            }
        }
        if(sBuf.length()>1){
            sBuf.delete(sBuf.length()-1, sBuf.length());
        }
        return sBuf.toString();
    }
    
  public static void main(String[] args) throws Exception {

//      
//      
//      java.util.List aList = new ArrayList();
//      System.out.println(UtilFuns.isNotEmpty(aList));
//      
//      System.out.println(uf.formatDateTimeCN("2011"));
//      System.out.println(uf.formatDateTimeCN("2011-01"));
//      System.out.println(uf.formatDateTimeCN("2011-01-02"));
//      System.out.println(uf.formatDateTimeCN("2011-01-02 03"));
//      System.out.println(uf.formatDateTimeCN("2011-01-02 13:05"));
//      System.out.println(uf.formatDateTimeCN("2011-01-02 13:05:05"));
//      System.out.println(uf.formatDateTimeCN("03"));
//      System.out.println(uf.formatDateTimeCN("13:05"));
//      System.out.println(uf.formatDateTimeCN("13:05:05"));
      
//      UtilFuns uf = new UtilFuns();
//      System.out.println(uf.getNoExistString("1,2,3", "1,2,3,4"));
//      System.out.println(uf.getNoExistString("安全,生產,營銷", "生產,營銷"));
//      System.out.println("finish!");
      
//      Set<String> set = new HashSet<String>();
//      set.add("abc");
//      set.add("xyz"); 
//      set.add("abc");  
//      for(Iterator<String> it = set.iterator();it.hasNext();){
//       System.out.println(it.next());   
//      } 
    
      /*
    System.out.println(SysTime("yyyy-MM-dd"));
    System.out.println(SysTime("yyyy-MM-dd HH:mm:ss"));
    
    System.out.println(Double.parseDouble("12.11"));
    System.out.println(FormatNumber("12.11000000000f"));
    
    System.out.println(getPatternString("CHEN ZISHU",8,0,".",3));
    */
    
    //System.out.println(SysTime("yyyy年MM月"));
    //System.out.println(SysTime("yyyyMM"));
    //System.out.println(ConvertSpaceTD(""));
    //System.out.println(ConvertTD(""));
    
        /* process the stat data Start 
        Statement stmt1 = conn.createStatement(); 
        String sTableName = find_Type;
        String sUserName = findName;
        StringBuffer sBuffer = new StringBuffer();

        //Step 1 clear Table userState
        sBuffer.append("delete * from userStat;");

        //Step 2 read username from User_P and write inputnum in it
        sBuffer.append("select User_P.loginname,").append(sTableName).append(".createby,count(").append(sTableName).append(".createby)")
            .append(" from ").append(sTableName).append("")
            .append(" right join")
            .append(" User_P")
            .append(" on User_P.loginname=").append(sTableName).append(".createby")
            .append(" where 1=1");
        if (find_Name.compareTo("")!=0){
            sBuffer.append(" and ").append(sTableName).append(".createby='").append(sTableName).append("'");
        }
        if (find_DateStart.compareTo("")!=0){
            sBuffer.append(" and createdate<='").append(find_DateStart).append(" 00:00:00'");
        }
        if (find_DateStart.compareTo("")!=0){
            sBuffer.append(" and createdate>='").append(find_DateEnd).append(" 23:59:59'");
        }
        sBuffer.append(" group by ").append(sTableName).append(".createby")
            .append(";");


        //Step 3 read updatenum
        sBuffer.append("select count(updateby) from ").append(sTableName).append("")
            .append(" where ").append(sTableName).append(".updateby=''")
            .append(" and updatedate<='").append(find_DateStart).append(" 00:00:00'")
            .append(" and updatedate>='").append(find_DateEnd).append(" 23:59:59'")
            .append(";");

        //Step 4 update the userStat.updatenum value
        sBuffer.append("update userStat set updatenum='3' where updateby='").append(sTableName).append("'")
            .append(";");

        sBuffer.toString();

         process the stat data End */

/*    
    try{
      System.out.println(SysDate());
       System.out.println(StrToDateTimeFormat("2003-08-21 18:28:47", "yyyy-MM-"));
    }catch(Exception e){
       
    }
    String s[] = SplitStr("asd,asd,we,sd",",");
    for (int curLayNum=0;curLayNum<s.length;curLayNum++){
      System.out.println(s[curLayNum]);
    }
    System.out.println(JoinStr(s,","));

    System.out.println(ReturnSysTime("yyyy-MM-dd"));
    //System.out.println(CoverDate(ReturnSysTime("yyyy-MM-dd HH:mm:ss"),"yyyy-MM-dd"));
    try {
      System.out.println(StrToTimestamp("2003-08-21 18:28:47", "yyyy-MM"));
      System.out.println(StrToDateTimeFormat("2003-08-21 18:28:47", "yyyy-MM"));
    }
    catch (ParseException ex) {
    }

    try {
      System.out.println(StrToTimestamp("2003-08-26", "yyyy-MM-dd"));
    }
    catch (ParseException ex) {
      System.out.println("StrToTimestamp error.");
    }*/
      
      System.out.println("finish!");
  }

/*
<script language=JavaScript>

  var today = new Date();
  var strDate = (today.getFullYear() + "年" +
(today.getMonth() + 1) + "月" + today.getDate() + "日 ");
  var n_day = today.getDay();
  switch (n_day)
  {
  case 0:{
  strDate = strDate + "星期日"
  }break;
  case 1:{
  strDate = strDate + "星期一"
  }break;
  case 2:{
  strDate = strDate + "星期二"
  }break;
  case 3:{
  strDate = strDate + "星期三"
  }break;
  case 4:{
  strDate = strDate + "星期四"
  }break;
  case 5:{
  strDate = strDate + "星期五"
  }break;
  case 6:{
  strDate = strDate + "星期六"
  }break;
  case 7:{
  strDate = strDate + "星期日"
  }break;
  }
  document.write(strDate);

</script>
*/

    public String replaceLast(String string, String toReplace, String replacement) {
        int pos = string.lastIndexOf(toReplace);
        if (pos > -1) {
            return string.substring(0, pos) + replacement + string.substring(pos + toReplace.length(), string.length());
        } else {
            return string;
        } 
    } 
    
    public static String getROOTPath(){
        UtilFuns uf = new UtilFuns();
        return uf.getClass().getResource("/").getPath().replace("/WEB-INF/classes/", "/").substring(1);
    }
    public String getClassRootPath(){
        return this.getClass().getResource("/").getPath();
    }
}

 

 

 

 MD5加密工具spring

 

package com.heima.bos.utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utils {
    /**
     * 使用md5的算法進行加密
     */
    public static String md5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(
                    plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("沒有md5這個算法!");
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);// 16進制數字
        // 若是生成數字未滿32位,須要前面補0
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }

    public static void main(String[] args) {
        System.out.println(md5("123"));
    }

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