web开发工具类

时间:2022-09-19 21:08:01

1.日期工具类

import java.text.SimpleDateFormat;

import java.util.Date;

public class DateUtil {

public static String formatDate(Date date,String format){
String result="";
SimpleDateFormat sdf=new SimpleDateFormat(format);
if(date!=null){
result=sdf.format(date);
}
return result;
}

public static Date formatString(String str,String format) throws Exception{
SimpleDateFormat sdf=new SimpleDateFormat(format);
return sdf.parse(str);
}
}

2.结果集转JSONArray工具类

import java.sql.ResultSet;

import java.sql.ResultSetMetaData;
import java.util.Date;

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

public class JsonUtil {

public static JSONArray formatRsToJsonArray(ResultSet rs)throws Exception{
ResultSetMetaData md=rs.getMetaData();
int num=md.getColumnCount();
JSONArray array=new JSONArray();
while(rs.next()){
JSONObject mapOfColValues=new JSONObject();
for(int i=1;i<=num;i++){
Object o=rs.getObject(i);
if(o instanceof Date){
mapOfColValues.put(md.getColumnName(i), DateUtil.formatDate((Date)o, "yyyy-MM-dd"));
}else{
mapOfColValues.put(md.getColumnName(i), rs.getObject(i));
}
}
array.add(mapOfColValues);
}
return array;
}
}

3.输出json字符串工具类

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

public class ResponseUtil {

public static void write(HttpServletResponse response,Object o)throws Exception{
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.println(o.toString());
out.flush();
out.close();
}
}

4.判断字符串空或非空工具类

public class StringUtil {

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

public static boolean isNotEmpty(String str){
if(!"".equals(str)&&str!=null){
return true;
}else{
return false;
}
}
}