整理收集的一些常用java工具类

1.json转换工具

1.package com.taotao.utils;3.import java.util.List;5.import com.fasterxml.jackson.core.JsonProcessingException;6.import com.fasterxml.jackson.databind.JavaType;7.import com.fasterxml.jackson.databind.JsonNode;8.import com.fasterxml.jackson.databind.ObjectMapper;10./**

11.  * json转换工具类

12.  */13.publicclassJsonUtils{15.// 定义jackson对象  16.privatestaticfinalObjectMapper MAPPER =newObjectMapper();18./** 19.  * 将对象转换成json字符串。 20.  *

Title: pojoToJson

21.  *

Description:

22.  *@paramdata 23.  *@return24.  */25.publicstaticString objectToJson(Object data) {26.try{27.String string = MAPPER.writeValueAsString(data);28.returnstring;29.}catch(JsonProcessingException e) {30.e.printStackTrace();31.}32.returnnull;33.}35./** 36.  * 将json结果集转化为对象 37.  *  38.  *@paramjsonData json数据 39.  *@paramclazz 对象中的object类型 40.  *@return41.  */42.publicstatic T jsonToPojo(String jsonData,ClassbeanType){43.try{44.T t = MAPPER.readValue(jsonData, beanType);45.returnt;46.}catch(Exceptione) {47.e.printStackTrace();48.}49.returnnull;50.}52./** 53.  * 将json数据转换成pojo对象list 54.  *

Title: jsonToList

55.  *

Description:

56.  *@paramjsonData 57.  *@parambeanType 58.  *@return59.  */60.publicstaticList jsonToList(String jsonData,ClassbeanType){61.JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);62.try{63.Listlist= MAPPER.readValue(jsonData, javaType);64.returnlist;65.}catch(Exceptione) {66.e.printStackTrace();67.}69.returnnull;70.}72.}

2.cookie的读写

1.packagecom.taotao.common.utils;3.importjava.io.UnsupportedEncodingException;4.importjava.net.URLDecoder;5.importjava.net.URLEncoder;7.importjavax.servlet.http.Cookie;8.importjavax.servlet.http.HttpServletRequest;9.importjavax.servlet.http.HttpServletResponse;12./**

13.  * 

14.  * Cookie 工具类

15.  *

16.  */17.publicfinalclassCookieUtils{19./** 20.  * 得到Cookie的值, 不编码 21.  *  22.  *@paramrequest 23.  *@paramcookieName 24.  *@return25.  */26.publicstaticStringgetCookieValue(HttpServletRequest request, String cookieName){27.returngetCookieValue(request, cookieName,false);28.  }30./** 31.  * 得到Cookie的值, 32.  *  33.  *@paramrequest 34.  *@paramcookieName 35.  *@return36.  */37.publicstaticStringgetCookieValue(HttpServletRequest request, String cookieName,booleanisDecoder){38.  Cookie[] cookieList = request.getCookies();39.if(cookieList ==null|| cookieName ==null) {40.returnnull;41.  }42.  String retValue =null;43.try{44.for(inti =0; i < cookieList.length; i++) {45.if(cookieList[i].getName().equals(cookieName)) {46.if(isDecoder) {47.  retValue = URLDecoder.decode(cookieList[i].getValue(),"UTF-8");48.  }else{49.  retValue = cookieList[i].getValue();50.  }51.break;52.  }53.  }54.  }catch(UnsupportedEncodingException e) {55.  e.printStackTrace();56.  }57.returnretValue;58.  }60./** 61.  * 得到Cookie的值, 62.  *  63.  *@paramrequest 64.  *@paramcookieName 65.  *@return66.  */67.publicstaticStringgetCookieValue(HttpServletRequest request, String cookieName, String encodeString){68.  Cookie[] cookieList = request.getCookies();69.if(cookieList ==null|| cookieName ==null) {70.returnnull;71.  }72.  String retValue =null;73.try{74.for(inti =0; i < cookieList.length; i++) {75.if(cookieList[i].getName().equals(cookieName)) {76.  retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);77.break;78.  }79.  }80.  }catch(UnsupportedEncodingException e) {81.  e.printStackTrace();82.  }83.returnretValue;84.  }86./**

87.  * 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码

88.  */89.publicstaticvoidsetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,90.String cookieValue){91.  setCookie(request, response, cookieName, cookieValue, -1);92.  }94./**

95.  * 设置Cookie的值 在指定时间内生效,但不编码

96.  */97.publicstaticvoidsetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,98.String cookieValue,intcookieMaxage){99.  setCookie(request, response, cookieName, cookieValue, cookieMaxage,false);100.  }102./**

103.  * 设置Cookie的值 不设置生效时间,但编码

104.  */105.publicstaticvoidsetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,106.String cookieValue,booleanisEncode){107.  setCookie(request, response, cookieName, cookieValue, -1, isEncode);108.  }110./**

111.  * 设置Cookie的值 在指定时间内生效, 编码参数

112.  */113.publicstaticvoidsetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,114.String cookieValue,intcookieMaxage,booleanisEncode){115.  doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);116.  }118./**

119.  * 设置Cookie的值 在指定时间内生效, 编码参数(指定编码)

120.  */121.publicstaticvoidsetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,122.String cookieValue,intcookieMaxage, String encodeString){123.  doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);124.  }126./**

127.  * 删除Cookie带cookie域名

128.  */129.publicstaticvoiddeleteCookie(HttpServletRequest request, HttpServletResponse response,130.String cookieName){131.  doSetCookie(request, response, cookieName,"", -1,false);132.  }134./** 135.  * 设置Cookie的值,并使其在指定时间内生效 136.  *  137.  *@paramcookieMaxage cookie生效的最大秒数 138.  */139.privatestaticfinalvoiddoSetCookie(HttpServletRequest request, HttpServletResponse response,140.String cookieName, String cookieValue,intcookieMaxage,booleanisEncode){141.try{142.if(cookieValue ==null) {143.  cookieValue ="";144.  }elseif(isEncode) {145.  cookieValue = URLEncoder.encode(cookieValue,"utf-8");146.  }147.  Cookie cookie =newCookie(cookieName, cookieValue);148.if(cookieMaxage >0)149.  cookie.setMaxAge(cookieMaxage);150.if(null!= request) {// 设置域名的cookie  151.  String domainName = getDomainName(request);152.  System.out.println(domainName);153.if(!"localhost".equals(domainName)) {154.  cookie.setDomain(domainName);155.  }156.  }157.  cookie.setPath("/");158.  response.addCookie(cookie);159.  }catch(Exception e) {160.  e.printStackTrace();161.  }162.  }164./** 165.  * 设置Cookie的值,并使其在指定时间内生效 166.  *  167.  *@paramcookieMaxage cookie生效的最大秒数 168.  */169.privatestaticfinalvoiddoSetCookie(HttpServletRequest request, HttpServletResponse response,170.String cookieName, String cookieValue,intcookieMaxage, String encodeString){171.try{172.if(cookieValue ==null) {173.  cookieValue ="";174.  }else{175.  cookieValue = URLEncoder.encode(cookieValue, encodeString);176.  }177.  Cookie cookie =newCookie(cookieName, cookieValue);178.if(cookieMaxage >0)179.  cookie.setMaxAge(cookieMaxage);180.if(null!= request) {// 设置域名的cookie  181.  String domainName = getDomainName(request);182.  System.out.println(domainName);183.if(!"localhost".equals(domainName)) {184.  cookie.setDomain(domainName);185.  }186.  }187.  cookie.setPath("/");188.  response.addCookie(cookie);189.  }catch(Exception e) {190.  e.printStackTrace();191.  }192.  }194./**

195.  * 得到cookie的域名

196.  */197.privatestaticfinalStringgetDomainName(HttpServletRequest request){198.  String domainName =null;200.  String serverName = request.getRequestURL().toString();201.if(serverName ==null|| serverName.equals("")) {202.  domainName ="";203.  }else{204.  serverName = serverName.toLowerCase();205.  serverName = serverName.substring(7);206.finalintend = serverName.indexOf("/");207.  serverName = serverName.substring(0, end);208.finalString[] domains = serverName.split("\\.");209.intlen = domains.length;210.if(len >3) {211.// www.xxx.com.cn  212.  domainName ="."+ domains[len -3] +"."+ domains[len -2] +"."+ domains[len -1];213.  }elseif(len <=3&& len >1) {214.// xxx.com or xxx.cn  215.  domainName ="."+ domains[len -2] +"."+ domains[len -1];216.  }else{217.  domainName = serverName;218.  }219.  }221.if(domainName !=null&& domainName.indexOf(":") >0) {222.  String[] ary = domainName.split("\\:");223.  domainName = ary[0];224.  }225.returndomainName;226.  }228.  }

3.HttpClientUtil

1.package com.taotao.utils;3.importjava.io.IOException;4.importjava.net.URI;5.importjava.util.ArrayList;6.importjava.util.List;7.importjava.util.Map;9.importorg.apache.http.NameValuePair;10.importorg.apache.http.client.entity.UrlEncodedFormEntity;11.importorg.apache.http.client.methods.CloseableHttpResponse;12.importorg.apache.http.client.methods.HttpGet;13.importorg.apache.http.client.methods.HttpPost;14.importorg.apache.http.client.utils.URIBuilder;15.importorg.apache.http.entity.ContentType;16.importorg.apache.http.entity.StringEntity;17.importorg.apache.http.impl.client.CloseableHttpClient;18.importorg.apache.http.impl.client.HttpClients;19.importorg.apache.http.message.BasicNameValuePair;20.importorg.apache.http.util.EntityUtils;22.publicclassHttpClientUtil{24.publicstaticStringdoGet(Stringurl,Map param) {26.// 创建Httpclient对象  27.CloseableHttpClient httpclient = HttpClients.createDefault();29.StringresultString ="";30.CloseableHttpResponse response =null;31.try{32.// 创建uri  33.URIBuilder builder =newURIBuilder(url);34.if(param !=null) {35.for(Stringkey : param.keySet()) {36.builder.addParameter(key, param.get(key));37.}38.}39.URI uri = builder.build();41.// 创建http GET请求  42.HttpGet httpGet =newHttpGet(uri);44.// 执行请求  45.response = httpclient.execute(httpGet);46.// 判断返回状态是否为200  47.if(response.getStatusLine().getStatusCode() ==200) {48.resultString = EntityUtils.toString(response.getEntity(),"UTF-8");49.}50.}catch(Exception e) {51.e.printStackTrace();52.}finally{53.try{54.if(response !=null) {55.response.close();56.}57.httpclient.close();58.}catch(IOException e) {59.e.printStackTrace();60.}61.}62.returnresultString;63.}65.publicstaticStringdoGet(Stringurl) {66.returndoGet(url,null);67.}69.publicstaticStringdoPost(Stringurl,Map param) {70.// 创建Httpclient对象  71.CloseableHttpClient httpClient = HttpClients.createDefault();72.CloseableHttpResponse response =null;73.StringresultString ="";74.try{75.// 创建Http Post请求  76.HttpPost httpPost =newHttpPost(url);77.// 创建参数列表  78.if(param !=null) {79.List paramList =newArrayList<>();80.for(Stringkey : param.keySet()) {81.paramList.add(newBasicNameValuePair(key, param.get(key)));82.}83.// 模拟表单  84.UrlEncodedFormEntity entity =newUrlEncodedFormEntity(paramList);85.httpPost.setEntity(entity);86.}87.// 执行http请求  88.response = httpClient.execute(httpPost);89.resultString = EntityUtils.toString(response.getEntity(),"utf-8");90.}catch(Exception e) {91.e.printStackTrace();92.}finally{93.try{94.response.close();95.}catch(IOException e) {96.// TODO Auto-generated catch block  97.e.printStackTrace();98.}99.}101.returnresultString;102.}104.publicstaticStringdoPost(Stringurl) {105.returndoPost(url,null);106.}108.publicstaticStringdoPostJson(Stringurl,Stringjson) {109.// 创建Httpclient对象  110.CloseableHttpClient httpClient = HttpClients.createDefault();111.CloseableHttpResponse response =null;112.StringresultString ="";113.try{114.// 创建Http Post请求  115.HttpPost httpPost =newHttpPost(url);116.// 创建请求内容  117.StringEntity entity =newStringEntity(json, ContentType.APPLICATION_JSON);118.httpPost.setEntity(entity);119.// 执行http请求  120.response = httpClient.execute(httpPost);121.resultString = EntityUtils.toString(response.getEntity(),"utf-8");122.}catch(Exception e) {123.e.printStackTrace();124.}finally{125.try{126.response.close();127.}catch(IOException e) {128.// TODO Auto-generated catch block  129.e.printStackTrace();130.}131.}133.returnresultString;134.}135.}

4.FastDFSClient工具类

1.packagecn.itcast.fastdfs.cliennt;3.importorg.csource.common.NameValuePair;4.importorg.csource.fastdfs.ClientGlobal;5.importorg.csource.fastdfs.StorageClient1;6.importorg.csource.fastdfs.StorageServer;7.importorg.csource.fastdfs.TrackerClient;8.importorg.csource.fastdfs.TrackerServer;10.publicclassFastDFSClient{12.privateTrackerClient trackerClient =null;13.privateTrackerServer trackerServer =null;14.privateStorageServer storageServer =null;15.privateStorageClient1 storageClient =null;17.publicFastDFSClient(String conf)throwsException{18.if(conf.contains("classpath:")) {19.  conf = conf.replace("classpath:",this.getClass().getResource("/").getPath());20.  }21.  ClientGlobal.init(conf);22.  trackerClient =newTrackerClient();23.  trackerServer = trackerClient.getConnection();24.  storageServer =null;25.  storageClient =newStorageClient1(trackerServer, storageServer);26.  }28./** 29.  * 上传文件方法 30.  *

Title: uploadFile

31.  *

Description:

32.  *@paramfileName 文件全路径 33.  *@paramextName 文件扩展名,不包含(.) 34.  *@parammetas 文件扩展信息 35.  *@return36.  *@throwsException 37.  */38.publicStringuploadFile(String fileName, String extName, NameValuePair[] metas)throwsException{39.  String result = storageClient.upload_file1(fileName, extName, metas);40.returnresult;41.  }43.publicStringuploadFile(String fileName)throwsException{44.returnuploadFile(fileName,null,null);45.  }47.publicStringuploadFile(String fileName, String extName)throwsException{48.returnuploadFile(fileName, extName,null);49.  }51./** 52.  * 上传文件方法 53.  *

Title: uploadFile

54.  *

Description:

55.  *@paramfileContent 文件的内容,字节数组 56.  *@paramextName 文件扩展名 57.  *@parammetas 文件扩展信息 58.  *@return59.  *@throwsException 60.  */61.publicStringuploadFile(byte[] fileContent, String extName, NameValuePair[] metas)throwsException{63.  String result = storageClient.upload_file1(fileContent, extName, metas);64.returnresult;65.  }67.publicStringuploadFile(byte[] fileContent)throwsException{68.returnuploadFile(fileContent,null,null);69.  }71.publicStringuploadFile(byte[] fileContent, String extName)throwsException{72.returnuploadFile(fileContent, extName,null);73.  }74.  }

1.publicclassFastDFSTest{[email protected] testFileUpload() throwsException{5.// 1、加载配置文件,配置文件中的内容就是tracker服务的地址。  6.ClientGlobal.init("D:/workspaces-itcast/term197/taotao-manager-web/src/main/resources/resource/client.conf");7.// 2、创建一个TrackerClient对象。直接new一个。  8.TrackerClient trackerClient =newTrackerClient();9.// 3、使用TrackerClient对象创建连接,获得一个TrackerServer对象。  10.TrackerServer trackerServer = trackerClient.getConnection();11.// 4、创建一个StorageServer的引用,值为null  12.StorageServer storageServer =null;13.// 5、创建一个StorageClient对象,需要两个参数TrackerServer对象、StorageServer的引用  14.StorageClient storageClient =newStorageClient(trackerServer, storageServer);15.// 6、使用StorageClient对象上传图片。  16.//扩展名不带“.”  17.String[] strings = storageClient.upload_file("D:/Documents/Pictures/images/200811281555127886.jpg","jpg",null);18.// 7、返回数组。包含组名和图片的路径。  19.for(String string : strings) {20.System.out.println(string);21.}22.}23.}# ![image](http://upload-images.jianshu.io/upload_images/2509688-45370c9d24b87e31?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

5.获取异常的堆栈信息

1.packagecom.taotao.utils;3.importjava.io.PrintWriter;4.importjava.io.StringWriter;6.publicclassExceptionUtil{8./** 9.  * 获取异常的堆栈信息 10.  *  11.  *@paramt 12.  *@return13.  */14.publicstaticStringgetStackTrace(Throwable t){15.  StringWriter sw =newStringWriter();16.  PrintWriter pw =newPrintWriter(sw);18.try{19.  t.printStackTrace(pw);20.returnsw.toString();21.  }finally{22.  pw.close();23.  }24.  }25.  }

#6.easyUIDataGrid对象返回值

1.packagecom.taotao.result;3.importjava.util.List;5./** 6.  * easyUIDataGrid对象返回值 7.  *

Title: EasyUIResult

8.  *

Description:

9.  *

Company: www.itcast.com

  10.  *@author入云龙 11.  *@date2015年7月21日下午4:12:52 12.  *@version1.0 13.  */14.publicclassEasyUIResult{16.privateInteger total;18.privateList rows;20.publicEasyUIResult(Integer total, List rows){21.this.total = total;22.this.rows = rows;23.  }25.publicEasyUIResult(longtotal, List rows){26.this.total = (int) total;27.this.rows = rows;28.  }30.publicIntegergetTotal(){31.returntotal;32.  }33.publicvoidsetTotal(Integer total){34.this.total = total;35.  }36.publicList getRows() {37.returnrows;38.  }39.publicvoidsetRows(List rows){40.this.rows = rows;41.  }44.  }

7.ftp上传下载工具类

1.packagecom.taotao.utils;3.importjava.io.File;4.importjava.io.FileInputStream;5.importjava.io.FileNotFoundException;6.importjava.io.FileOutputStream;7.importjava.io.IOException;8.importjava.io.InputStream;9.importjava.io.OutputStream;11.importorg.apache.commons.net.ftp.FTP;12.importorg.apache.commons.net.ftp.FTPClient;13.importorg.apache.commons.net.ftp.FTPFile;14.importorg.apache.commons.net.ftp.FTPReply;16./** 17.  * ftp上传下载工具类 18.  *

Title: FtpUtil

19.  *

Description:

20.  *

Company: www.itcast.com

  21.  *@author入云龙 22.  *@date2015年7月29日下午8:11:51 23.  *@version1.0 24.  */25.publicclassFtpUtil{27./**  28.  * Description: 向FTP服务器上传文件  29.  *@paramhost FTP服务器hostname  30.  *@paramport FTP服务器端口  31.  *@paramusername FTP登录账号  32.  *@parampassword FTP登录密码  33.  *@parambasePath FTP服务器基础目录 34.  *@paramfilePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath 35.  *@paramfilename 上传到FTP服务器上的文件名  36.  *@paraminput 输入流  37.  *@return成功返回true,否则返回false  38.  */39.publicstaticbooleanuploadFile(String host,intport, String username, String password, String basePath,40.String filePath, String filename, InputStream input){41.booleanresult =false;42.  FTPClient ftp =newFTPClient();43.try{44.intreply;45.  ftp.connect(host, port);// 连接FTP服务器  46.// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器  47.  ftp.login(username, password);// 登录  48.  reply = ftp.getReplyCode();49.if(!FTPReply.isPositiveCompletion(reply)) {50.  ftp.disconnect();51.returnresult;52.  }53.//切换到上传目录  54.if(!ftp.changeWorkingDirectory(basePath+filePath)) {55.//如果目录不存在创建目录  56.  String[] dirs = filePath.split("/");57.  String tempPath = basePath;58.for(String dir : dirs) {59.if(null== dir ||"".equals(dir))continue;60.  tempPath +="/"+ dir;61.if(!ftp.changeWorkingDirectory(tempPath)) {62.if(!ftp.makeDirectory(tempPath)) {63.returnresult;64.  }else{65.  ftp.changeWorkingDirectory(tempPath);66.  }67.  }68.  }69.  }70.//设置上传文件的类型为二进制类型  71.  ftp.setFileType(FTP.BINARY_FILE_TYPE);72.//上传文件  73.if(!ftp.storeFile(filename, input)) {74.returnresult;75.  }76.  input.close();77.  ftp.logout();78.  result =true;79.  }catch(IOException e) {80.  e.printStackTrace();81.  }finally{82.if(ftp.isConnected()) {83.try{84.  ftp.disconnect();85.  }catch(IOException ioe) {86.  }87.  }88.  }89.returnresult;90.  }92./**  93.  * Description: 从FTP服务器下载文件  94.  *@paramhost FTP服务器hostname  95.  *@paramport FTP服务器端口  96.  *@paramusername FTP登录账号  97.  *@parampassword FTP登录密码  98.  *@paramremotePath FTP服务器上的相对路径  99.  *@paramfileName 要下载的文件名  100.  *@paramlocalPath 下载后保存到本地的路径  101.  *@return102.  */103.publicstaticbooleandownloadFile(String host,intport, String username, String password, String remotePath,104.String fileName, String localPath){105.booleanresult =false;106.  FTPClient ftp =newFTPClient();107.try{108.intreply;109.  ftp.connect(host, port);110.// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器  111.  ftp.login(username, password);// 登录  112.  reply = ftp.getReplyCode();113.if(!FTPReply.isPositiveCompletion(reply)) {114.  ftp.disconnect();115.returnresult;116.  }117.  ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录  118.  FTPFile[] fs = ftp.listFiles();119.for(FTPFile ff : fs) {120.if(ff.getName().equals(fileName)) {121.  File localFile =newFile(localPath +"/"+ ff.getName());123.  OutputStream is =newFileOutputStream(localFile);124.  ftp.retrieveFile(ff.getName(), is);125.  is.close();126.  }127.  }129.  ftp.logout();130.  result =true;131.  }catch(IOException e) {132.  e.printStackTrace();133.  }finally{134.if(ftp.isConnected()) {135.try{136.  ftp.disconnect();137.  }catch(IOException ioe) {138.  }139.  }140.  }141.returnresult;142.  }144.publicstaticvoidmain(String[] args){145.try{146.  FileInputStream in=newFileInputStream(newFile("D:\\temp\\image\\gaigeming.jpg"));147.booleanflag = uploadFile("192.168.25.133",21,"ftpuser","ftpuser","/home/ftpuser/www/images","/2015/01/21","gaigeming.jpg", in);148.  System.out.println(flag);149.  }catch(FileNotFoundException e) {150.  e.printStackTrace();151.  }152.  }153.  }

8.各种id生成策略

1.package com.taotao.utils;3.importjava.util.Random;5./**

6.  * 各种id生成策略

7.  *

Title: IDUtils

8.  *

Description:

9.  * @date    2015年7月22日下午2:32:10

10.  * @version 1.0

11.  */12.publicclassIDUtils{14./**

15.  * 图片名生成

16.  */17.publicstaticStringgenImageName(){18.//取当前时间的长整形值包含毫秒  19.longmillis = System.currentTimeMillis();20.//long millis = System.nanoTime();  21.//加上三位随机数  22.Random random =newRandom();23.intend3 = random.nextInt(999);24.//如果不足三位前面补0  25.String str = millis + String.format("%03d", end3);27.returnstr;28.}30./**

31.  * 商品id生成

32.  */33.publicstaticlonggenItemId(){34.//取当前时间的长整形值包含毫秒  35.longmillis = System.currentTimeMillis();36.//long millis = System.nanoTime();  37.//加上两位随机数  38.Random random =newRandom();39.intend2 = random.nextInt(99);40.//如果不足两位前面补0  41.String str = millis + String.format("%02d", end2);42.longid =newLong(str);43.returnid;44.}46.publicstaticvoidmain(String[] args){47.for(inti=0;i<100;i++)48.System.out.println(genItemId());49.}50.}

##9.上传图片返回值

1.package com.result;2./**

3.  * 上传图片返回值

4.  *

Title: PictureResult

5.  *

Description:

6.  *

Company: www.itcast.com

 

7.  * @author  入云龙

8.  * @date    2015年7月22日下午2:09:02

9.  * @version 1.0

10.  */11.publicclassPictureResult{13./**

14.  * 上传图片返回值,成功:0 失败:1   

15.  */16.privateInteger error;17./**

18.  * 回显图片使用的url

19.  */20.privateString url;21./**

22.  * 错误时的错误消息

23.  */24.privateString message;25.publicPictureResult(Integer state, String url){26.this.url = url;27.this.error = state;28.}29.publicPictureResult(Integer state, String url, String errorMessage){30.this.url = url;31.this.error = state;32.this.message = errorMessage;33.}34.publicIntegergetError(){35.returnerror;36.}37.publicvoidsetError(Integer error){38.this.error = error;39.}40.publicStringgetUrl(){41.returnurl;42.}43.publicvoidsetUrl(String url){44.this.url = url;45.}46.publicStringgetMessage(){47.returnmessage;48.}49.publicvoidsetMessage(String message){50.this.message = message;51.}53.}

10.自定义响应结构

1.packagecom.result;3.importjava.util.List;5.importcom.fasterxml.jackson.databind.JsonNode;6.importcom.fasterxml.jackson.databind.ObjectMapper;8./**

9.  * 自定义响应结构

10.  */11.publicclassTaotaoResult{13.// 定义jackson对象  14.privatestaticfinalObjectMapper MAPPER =newObjectMapper();16.// 响应业务状态  17.privateInteger status;19.// 响应消息  20.privateString msg;22.// 响应中的数据  23.privateObject data;25.publicstaticTaotaoResultbuild(Integer status, String msg, Object data){26.returnnewTaotaoResult(status, msg, data);27.  }29.publicstaticTaotaoResultok(Object data){30.returnnewTaotaoResult(data);31.  }33.publicstaticTaotaoResultok(){34.returnnewTaotaoResult(null);35.  }37.publicTaotaoResult(){39.  }41.publicstaticTaotaoResultbuild(Integer status, String msg){42.returnnewTaotaoResult(status, msg,null);43.  }45.publicTaotaoResult(Integer status, String msg, Object data){46.this.status = status;47.this.msg = msg;48.this.data = data;49.  }51.publicTaotaoResult(Object data){52.this.status =200;53.this.msg ="OK";54.this.data = data;55.  }57.//    public Boolean isOK() {  58.//        return this.status == 200;  59.//    }  61.publicIntegergetStatus(){62.returnstatus;63.  }65.publicvoidsetStatus(Integer status){66.this.status = status;67.  }69.publicStringgetMsg(){70.returnmsg;71.  }73.publicvoidsetMsg(String msg){74.this.msg = msg;75.  }77.publicObjectgetData(){78.returndata;79.  }81.publicvoidsetData(Object data){82.this.data = data;83.  }85./** 86.  * 将json结果集转化为TaotaoResult对象 87.  *  88.  *@paramjsonData json数据 89.  *@paramclazz TaotaoResult中的object类型 90.  *@return91.  */92.publicstaticTaotaoResultformatToPojo(String jsonData, Class clazz){93.try{94.if(clazz ==null) {95.returnMAPPER.readValue(jsonData, TaotaoResult.class);96.  }97.  JsonNode jsonNode = MAPPER.readTree(jsonData);98.  JsonNode data = jsonNode.get("data");99.  Object obj =null;100.if(clazz !=null) {101.if(data.isObject()) {102.  obj = MAPPER.readValue(data.traverse(), clazz);103.  }elseif(data.isTextual()) {104.  obj = MAPPER.readValue(data.asText(), clazz);105.  }106.  }107.returnbuild(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj);108.  }catch(Exception e) {109.returnnull;110.  }111.  }113./** 114.  * 没有object对象的转化 115.  *  116.  *@paramjson 117.  *@return118.  */119.publicstaticTaotaoResultformat(String json){120.try{121.returnMAPPER.readValue(json, TaotaoResult.class);122.  }catch(Exception e) {123.  e.printStackTrace();124.  }125.returnnull;126.  }128./** 129.  * Object是集合转化 130.  *  131.  *@paramjsonData json数据 132.  *@paramclazz 集合中的类型 133.  *@return134.  */135.publicstaticTaotaoResultformatToList(String jsonData, Class clazz){136.try{137.  JsonNode jsonNode = MAPPER.readTree(jsonData);138.  JsonNode data = jsonNode.get("data");139.  Object obj =null;140.if(data.isArray() && data.size() >0) {141.  obj = MAPPER.readValue(data.traverse(),142.  MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));143.  }144.returnbuild(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj);145.  }catch(Exception e) {146.returnnull;147.  }148.  }150.  }

##11.jedis操作

1.package com.taotao.jedis;3.public interface JedisClient {5.Stringset(Stringkey,Stringvalue);6.Stringget(Stringkey);7.Booleanexists(Stringkey);8.Long expire(Stringkey, int seconds);9.Long ttl(Stringkey);10.Long incr(Stringkey);11.Long hset(Stringkey,Stringfield,Stringvalue);12.Stringhget(Stringkey,Stringfield);13.Long hdel(Stringkey,String... field);14.}

1.packagecom.taotao.jedis;3.importorg.springframework.beans.factory.annotation.Autowired;5.importredis.clients.jedis.JedisCluster;7.publicclassJedisClientClusterimplementsJedisClient{[email protected] jedisCluster;[email protected](String key, String value){14.returnjedisCluster.set(key, value);15.  }[email protected](String key){19.returnjedisCluster.get(key);20.  }[email protected](String key){24.returnjedisCluster.exists(key);25.  }[email protected](String key,intseconds){29.returnjedisCluster.expire(key, seconds);30.  }[email protected](String key){34.returnjedisCluster.ttl(key);35.  }[email protected](String key){39.returnjedisCluster.incr(key);40.  }[email protected](String key, String field, String value){44.returnjedisCluster.hset(key, field, value);45.  }[email protected](String key, String field){49.returnjedisCluster.hget(key, field);50.  }[email protected](String key, String... field){54.returnjedisCluster.hdel(key, field);55.  }57.  }

1.packagecom.taotao.jedis;4.importorg.springframework.beans.factory.annotation.Autowired;7.importredis.clients.jedis.Jedis;8.importredis.clients.jedis.JedisPool;11.publicclassJedisClientPoolimplementsJedisClient{[email protected] jedisPool;[email protected](String key, String value){19.  Jedis jedis = jedisPool.getResource();20.  String result = jedis.set(key, value);21.  jedis.close();22.returnresult;23.  }[email protected](String key){28.  Jedis jedis = jedisPool.getResource();29.  String result = jedis.get(key);30.  jedis.close();31.returnresult;32.  }[email protected](String key){37.  Jedis jedis = jedisPool.getResource();38.  Boolean result = jedis.exists(key);39.  jedis.close();40.returnresult;41.  }[email protected](String key,intseconds){46.  Jedis jedis = jedisPool.getResource();47.  Long result = jedis.expire(key, seconds);48.  jedis.close();49.returnresult;50.  }[email protected](String key){55.  Jedis jedis = jedisPool.getResource();56.  Long result = jedis.ttl(key);57.  jedis.close();58.returnresult;59.  }[email protected](String key){64.  Jedis jedis = jedisPool.getResource();65.  Long result = jedis.incr(key);66.  jedis.close();67.returnresult;68.  }[email protected](String key, String field, String value){73.  Jedis jedis = jedisPool.getResource();74.  Long result = jedis.hset(key, field, value);75.  jedis.close();76.returnresult;77.  }[email protected](String key, String field){82.  Jedis jedis = jedisPool.getResource();83.  String result = jedis.hget(key, field);84.  jedis.close();85.returnresult;86.  }[email protected](String key, String... field){91.  Jedis jedis = jedisPool.getResource();92.  Long result = jedis.hdel(key, field);93.  jedis.close();94.returnresult;95.  }98.  }  本文作者:[一个小迷糊][阅读原文]([http://click.aliyun.com/m/50526/]本文为云栖社区原创内容,未经允许不得转载。

你可能感兴趣的:(整理收集的一些常用java工具类)