controller层日期转换通用类

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通用类的接口和实现类

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);
}
}

文件下载工具类

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 = ;
int readLength=;
byte buf[] = new byte[];
readLength = inputStream.read(buf, , length);
while (readLength != -) {
outputStream.write(buf, , readLength);
readLength = inputStream.read(buf, , 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(); //刷数据
}
}

 购销合同模块映射文件作为例子

<?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 = -->
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),)
+
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))
,)) 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 =
<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定义),
无效的列类型: ; 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 > ) {
return true;
} else {
return false;
}
} /* 验证list是否为空 */
public boolean listValid(List list) {
if (list != null && list.size() > ) {
return true;
} else {
return false;
}
} //获得年龄
public int age(String dateStart, String dateEnd) throws Exception{
int yearStart = Integer.parseInt(dateStart.substring(,));
int yearEnd = Integer.parseInt(dateEnd.substring(,));
return yearEnd-yearStart;
} //是否为奇数
public boolean isOdd(int i){
if(i%==){
return false;
}else{
return true;
}
} public String cutStr(String str,int len){
try{
str = str.substring(,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=;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=;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(,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(, 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 =;
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=;i<_temp.length;i++){
_temp[i] = _temp[i-]+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=;i<aStr.length;i++){
sBuffer.append(aStr[i]).append(SplitFlag);
}
sBuffer.delete(sBuffer.length() - , 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=;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=;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=;i<aStr.length;i++){
sBuffer.append("'").append(aStr[i]).append("'").append(",");
}
sBuffer.delete(sBuffer.length() - , 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=;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=;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=;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("")==){
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<=){
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()<=){
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()==){
return "";
}else{
return strvalue.trim();
}
}catch(Exception e){
return "";
}
} public static String[] convertNull(String[] aContent)
{
try{
for(int i=;i<aContent.length;i++){
if(aContent[i].toLowerCase().compareTo("null")==){
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()==){
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 ;
}else{
return Integer.parseInt(s);
}
}catch(Exception e){
return ;
}
} //将为null的数据转为0,用在数值的值从数据库中读出的情况
public static int cvtPecrent(Object o)
{
try{
String s = convertNull(o);
if(s==""){
return ;
}else{
return Integer.parseInt(s);
}
}catch(Exception e){
return ;
}
} //if 0 then return "";
public static String FormatZero(Object o)
{
try{
String s = convertNull(o);
if(s.compareTo("")==){
return "";
}else if(s.compareTo("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("")==){
return "";
}else{
return s;
}
}catch(Exception e){
return "";
}
} //patter="####.000"
public static String FormatNumber(Object o,String patter)
{
double d = ;
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 = ;
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()==){
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()==){
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()==){
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(, );
a = a.toUpperCase();
return a + source.substring(); } /**
* 将字符串转换成Long型
* @param param 传入字符串
* @return 长整形
*/
public static long parseLong(String param) {
long l=;
try {
l = Long.parseLong(param);
}
catch (Exception e) {
} return l;
} /**
* 将字符串转换成Float型
* @param param 传入字符串
* @return 浮点型
*/
public static float parseFloat(String param) {
float l=;
try {
l = Float.parseFloat(param);
}
catch (Exception e) {
} return l;
} /**
* 将字符串转换成Integer型
* @param param 传入字符串
* @return 整形
*/
public static int parseInt(String param) {
int l=;
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=;
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 = ; i < aList.size(); i ++) {
if (s.equals(aList.get(i))){
return i;
}
}
}catch(Exception e){ }
return -;
} /**
* s是否存在String数组中,存在返回数组下标,不存在返回-1
*/
public static int existElements(String s,String[] a) {
try{
for (int i = ; i < a.length; i ++) {
if (s.compareTo((a[i].trim()))==){
return i;
}
}
}catch(Exception e){ }
return -;
} /**
* 判断对象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 = ; i < aList.size(); i ++) {
s1 = String.valueOf(aList.get(i));
if (s1.indexOf(s)!=-){
return i;
}
}
}catch(Exception e){ }
return -;
} /**
* 将ArrayList转换为一维String数组,并把其中的null换成空字符串
* @param aList 传入的Arraylist
*/
public String[] ArrayListToString(ArrayList aList) {
String[] s = new String[aList.size()];
for (int i = ; 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 = ; 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 = ;
StringBuffer sBuf = new StringBuffer();
String selected = " selected";
try{
sBuf.append("<option value='' selected>--请选择--</option>");
for (i = ; i < content.length; i++) {
sBuf.append("\n<option value='").append(i).append("'");
if (CurrentValue.compareTo(String.valueOf(i)) == ) {
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 = ;
StringBuffer sBuf = new StringBuffer();
String selected = " selected";
try{
for (i = ; i < content.length; i++) {
sBuf.append("\n<option value='").append(i).append("'");
if (CurrentValue.compareTo(String.valueOf(i)) == ) {
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 = ;
StringBuffer sBuf = new StringBuffer();
String selected = " selected"; try{
if(CurrentValue==null){
CurrentValue = "";
}
sBuf.append("<option value='' selected>--请选择--</option>");
for (i = ; i < content.length; i++) {
sBuf.append("<option value='").append(values[i]).append("'");
if (CurrentValue.compareTo(values[i]) == ) {
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 = ;
StringBuffer sBuf = new StringBuffer();
String selected = " selected"; try{
for (i = ; i < content.length; i++) {
sBuf.append("<option value='").append(values[i]).append("'");
if (CurrentValue.compareTo(values[i]) == ) {
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(,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(,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(,"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(".")>-){
date = date.substring(, date.indexOf("."));
}
if(date.length()==){ //yyyy
s = date+"年";
}else if(date.length()==){ //yyyy-MM
s = date.replaceAll("-0", "-").replaceFirst("-", "年")+"月";
}else if(date.length()==){ //yyyy-MM-dd
s = date.replaceAll("-0", "-").replaceFirst("-", "年").replaceFirst("-", "月")+"日";
}else if(date.length()==){ //HH
s = date+"时";
}else if(date.length()==){ //HH:mm
s = date.replaceAll(":0", ":").replaceFirst(":", "时")+"分";
}else if(date.length()==){ //HH:mm:ss
s = date.replaceAll(":0", ":").replaceFirst(":", "时").replaceFirst(":", "分")+"秒";
}else if(date.length()==){ //yyyy-MM-dd HH
s = date.replaceAll("-0", "-").replaceFirst("-", "年").replaceFirst("-", "月").replaceAll("", " ").replaceFirst(" ", "日")+"时";
}else if(date.length()==){ //yyyy-MM-dd HH:mm
s = date.replaceAll("-0", "-").replaceFirst("-", "年").replaceFirst("-", "月").replaceAll("", " ").replaceFirst(" ", "日").replaceAll(":0", ":").replaceFirst(":", "时")+"分";
}else if(date.length()==){ //yyyy-MM-dd HH:mm:ss
s = date.replaceAll("-0", "-").replaceFirst("-", "年").replaceFirst("-", "月").replaceAll("", " ").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 = ;
try{
if(UtilFuns.isEmpty(date)){
return "";
}
String[] aString = date.replaceAll("-0", "-").split("-");
whichMonth = Integer.parseInt(aString[]);
if(whichMonth==){
s = "Jan";
}else if(whichMonth==){
s = "Feb";
}else if(whichMonth==){
s = "Mar";
}else if(whichMonth==){
s = "Apr";
}else if(whichMonth==){
s = "May";
}else if(whichMonth==){
s = "Jun";
}else if(whichMonth==){
s = "Jul";
}else if(whichMonth==){
s = "Aug";
}else if(whichMonth==){
s = "Sept";
}else if(whichMonth==){
s = "Oct";
}else if(whichMonth==){
s = "Nov";
}else if(whichMonth==){
s = "Dec";
}
s = s+"."+aString[]+","+aString[]; }catch(Exception e){ } return s;
} //返回年月格式 2010-7
public String formatShortMonth(String strDate){
return strDate.substring(,).replaceAll("-0", "-");
} //返回年月格式 2010-07
public String formatMonth(String strDate){
return strDate.substring(,);
} //删除最后1个字符
public static String delLastChar(String s){
try{
if(s.length()>){
s = s.substring(,s.length()-);
}
}catch(Exception e){
return "";
}
return s;
} //删除最后len个字符
public static String delLastChars(String s,int len){
try{
if(s.length()>){
s = s.substring(,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("")==){
return "";
} else {
int intStrvalue = strvalue.length();
if ( intStrvalue > Flag ) {
strvalue = strvalue.substring( , intStrvalue - Flag ); }
for ( int i = ; 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( , Flag );
strvalue2 = strvalue.substring( sFlag, intStrvalue );
} else {
strvalue1 = "";
strvalue2 = "";
}
for ( int i = ; 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==) {
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( , iStartPos );
}else{
return s;
}
if ( ints > iEndPos) {
sEndStr = s.substring( iEndPos, ints );
}
for ( int i = ; 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,,sPattern,iPatternLen);
} public static String getPatternString( String s, int iStartPos, String sPattern ) {
return getPatternString(s,iStartPos,,sPattern,);
} /** 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==){
return "";
}
StringBuffer sBuf = new StringBuffer();
for(int i=;i<allString.length;i++){
if(existString.indexOf(allString[i])==-){
sBuf.append(allString[i]).append(",");
}
}
if(sBuf.length()>){
sBuf.delete(sBuf.length()-, 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 > -) {
return string.substring(, 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();
}
public String getClassRootPath(){
return this.getClass().getResource("/").getPath();
}
}

 MD5加密工具

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(, secretBytes).toString();// 16进制数字
// 如果生成数字未满32位,需要前面补0
for (int i = ; i < - md5code.length(); i++) {
md5code = "" + md5code;
}
return md5code;
} public static void main(String[] args) {
System.out.println(md5(""));
} }

ssm项目开发通用base模块和工具的更多相关文章

  1. 第二章 企业项目开发--maven父子模块

    2.1.maven父子模块 在实际开发中,我们基本都会用maven父子分模块的方式进行项目的开发. 2.2.实际操作 2.2.1.手工建立一个ssmm0的文件夹,并在该文件夹中加入一个pom.xml文 ...

  2. SSM项目开发中的实体定义以及MySQL表格设计

    话不多说,下面表格是项目开发中用到的实体集以及表格Name 实体创建     表格创建 Area 区域 Area 实体 areaId areaName priority createTime last ...

  3. IDEA 学习笔记之 Java项目开发

    Java项目开发: 新建模块: 添加JDK: 导入本地Jars: 从远程Maven仓库下载: 创建package: 新建类/接口/枚举等: 字体太小,改字体: Duplicate Scheme 修改编 ...

  4. SpringBoot项目创建与第一个SSM项目示例

    本节介绍SpringBoot创建第一个示例SSM项目的完整过程,使用工具STS,与IDEA操作基本类似. 示例代码在:https://github.com/laolunsi/spring-boot-e ...

  5. 配置一个简单的传统SSM项目

    背景 我们知道,从2002年开始,Spring一直在飞速的发展,如今已经成为了在Java EE开发中的标准,早期的项目都是传统的Spring-SpringMVC-Mybatis项目,打成一个war包丢 ...

  6. SSM框架开发web项目系列(五) Spring集成MyBatis

    前言 在前面的MyBatis部分内容中,我们已经可以独立的基于MyBatis构建一个数据库访问层应用,但是在实际的项目开发中,我们的程序不会这么简单,层次也更加复杂,除了这里说到的持久层,还有业务逻辑 ...

  7. 使用Jquery+EasyUI 进行框架项目开发案例讲解之五 模块(菜单)管理源码分享

    http://www.cnblogs.com/huyong/p/3454012.html 使用Jquery+EasyUI 进行框架项目开发案例讲解之五  模块(菜单)管理源码分享    在上四篇文章 ...

  8. PhpStorm创建Drupal模块项目开发教程(4)

    编码器是一个检查和操纵代码的Drupal-specific工具. 探测器则是发现异常代码,通常被用于开发中的编码错误预警. 接下来将介绍编码器与探测器在PhpStorm中整合工作的各个步骤,实现PHP ...

  9. PhpStorm创建Drupal模块项目开发教程

    在PhpStorm开发工具中,创建Drupal开发项目有两种方式:整合Drupal到现有的项目中和直接创建一个新的Drupal模块. 接下来将展示这两种方式的具体操作! 整合Drupal到现有的项目 ...

随机推荐

  1. HTTP协议详解之User Agent篇

    •User Agent:用户代理 指浏览器他的信息包括硬件平台.系统软件.应用软件和用户个人偏好.用户代理不仅仅指浏览器,还包括搜索引擎. •为什么所有浏览器的User Agent都带有Mozilla ...

  2. &和&&的一点区别

    &两边的语句都会执行,&&有可能只执行左边的语句. &做位运算与的时候可以更高效的判断一个数字是不是奇数. 1&1 = 1 0&1 = 0 所以和1与结 ...

  3. 在Ubuntu16.04 64bit上安装sublime text 3

    安装sublime text 3 根据官网上提供的安装说明 https://www.sublimetext.com/docs/3/linux_repositories.html  进行安装, 首先是 ...

  4. cocos2d-x 旅程開始--(实现单击与长按)

    小菜鸟一枚,学习cocos2d-x已经有一段时间了,感觉进度非常慢那,CSDN也再次拾了起来.近期自己还在学习做小游戏,跟着前辈做了<忍者打怪物>的小游戏,又学习了瓦片游戏<吃西瓜& ...

  5. nginx反向代理proxy_set_header自定义header头无效

    公司使用nginx作为负载均衡,有时候需要自定义header头发送给后端的真实服务器. 想过去应该是非常的简单的事情. 例子如下: 设置代理服务器ip头   1 proxy_set_header X- ...

  6. HDUOJ-----(1072)Nightmare(bfs)

    Nightmare Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total ...

  7. 32个Chrome 针对网页设计师和开发人员扩展

    http://zmingcx.com/32-chrome-web-designers-and-developers-to-expand.html

  8. 如何判断Android手机当前是否联网?

    如果拟开发一个网络应用的程序,首先考虑是否接入网络,在Android手机中判断是否联网可以通过 ConnectivityManager 类的isAvailable()方法判断, 首先获取网络通讯类的实 ...

  9. iOS - UnitTests 单元测试

    1.UnitTests 在计算机编程中,单元测试(又称为模块测试, Unit Testing)是针对程序模块(软件设计的最小单位)来进行正确性检验的测试工作.程序单元是应用的最小可测试部件.在过程化编 ...

  10. windows平台安装redis服务

    有时候我们需要在windows平台上使用redis作为缓存服务,这个时候就需要将redis安装为window服务. 现在将我安装过程记录下来,方便自己或者有类似需求的同学参考.主要是参考网上现有的例子 ...