整理收集的一些經常使用java工具類

摘要: 1.json轉換工具 [java] view plain copy package com.taotao.utils; import java.util.List; import com.java

1.json轉換工具

[java] view plain copy
package com.taotao.utils;  
  
import java.util.List;  
  
import com.fasterxml.jackson.core.JsonProcessingException;  
import com.fasterxml.jackson.databind.JavaType;  
import com.fasterxml.jackson.databind.JsonNode;  
import com.fasterxml.jackson.databind.ObjectMapper;  
  
/** 
 * json轉換工具類 
 */  
public class JsonUtils {  
  
    // 定義jackson對象  
    private static final ObjectMapper MAPPER = new ObjectMapper();  
  
    /** 
     * 將對象轉換成json字符串。 
     * <p>Title: pojoToJson</p> 
     * <p>Description: </p> 
     * @param data 
     * @return 
     */  
    public static String objectToJson(Object data) {  
        try {  
            String string = MAPPER.writeValueAsString(data);  
            return string;  
        } catch (JsonProcessingException e) {  
            e.printStackTrace();  
        }  
        return null;  
    }  
      
    /** 
     * 將json結果集轉化爲對象 
     *  
     * @param jsonData json數據 
     * @param clazz 對象中的object類型 
     * @return 
     */  
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {  
        try {  
            T t = MAPPER.readValue(jsonData, beanType);  
            return t;  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return null;  
    }  
      
    /** 
     * 將json數據轉換成pojo對象list 
     * <p>Title: jsonToList</p> 
     * <p>Description: </p> 
     * @param jsonData 
     * @param beanType 
     * @return 
     */  
    public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {  
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);  
        try {  
            List<T> list = MAPPER.readValue(jsonData, javaType);  
            return list;  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
          
        return null;  
    }  
      
}

2.cookie的讀寫

[java] view plain copy
package com.taotao.common.utils;  
  
import java.io.UnsupportedEncodingException;  
import java.net.URLDecoder;  
import java.net.URLEncoder;  
  
import javax.servlet.http.Cookie;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
  
/** 
 *  
 * Cookie 工具類 
 * 
 */  
public final class CookieUtils {  
  
    /** 
     * 獲得Cookie的值, 不編碼 
     *  
     * @param request 
     * @param cookieName 
     * @return 
     */  
    public static String getCookieValue(HttpServletRequest request, String cookieName) {  
        return getCookieValue(request, cookieName, false);  
    }  
  
    /** 
     * 獲得Cookie的值, 
     *  
     * @param request 
     * @param cookieName 
     * @return 
     */  
    public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {  
        Cookie[] cookieList = request.getCookies();  
        if (cookieList == null || cookieName == null) {  
            return null;  
        }  
        String retValue = null;  
        try {  
            for (int i = 0; i < cookieList.length; i++) {  
                if (cookieList[i].getName().equals(cookieName)) {  
                    if (isDecoder) {  
                        retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");  
                    } else {  
                        retValue = cookieList[i].getValue();  
                    }  
                    break;  
                }  
            }  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
        return retValue;  
    }  
  
    /** 
     * 獲得Cookie的值, 
     *  
     * @param request 
     * @param cookieName 
     * @return 
     */  
    public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) {  
        Cookie[] cookieList = request.getCookies();  
        if (cookieList == null || cookieName == null) {  
            return null;  
        }  
        String retValue = null;  
        try {  
            for (int i = 0; i < cookieList.length; i++) {  
                if (cookieList[i].getName().equals(cookieName)) {  
                    retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);  
                    break;  
                }  
            }  
        } catch (UnsupportedEncodingException e) {  
             e.printStackTrace();  
        }  
        return retValue;  
    }  
  
    /** 
     * 設置Cookie的值 不設置生效時間默認瀏覽器關閉即失效,也不編碼 
     */  
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,  
            String cookieValue) {  
        setCookie(request, response, cookieName, cookieValue, -1);  
    }  
  
    /** 
     * 設置Cookie的值 在指定時間內生效,但不編碼 
     */  
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,  
            String cookieValue, int cookieMaxage) {  
        setCookie(request, response, cookieName, cookieValue, cookieMaxage, false);  
    }  
  
    /** 
     * 設置Cookie的值 不設置生效時間,但編碼 
     */  
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,  
            String cookieValue, boolean isEncode) {  
        setCookie(request, response, cookieName, cookieValue, -1, isEncode);  
    }  
  
    /** 
     * 設置Cookie的值 在指定時間內生效, 編碼參數 
     */  
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,  
            String cookieValue, int cookieMaxage, boolean isEncode) {  
        doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);  
    }  
  
    /** 
     * 設置Cookie的值 在指定時間內生效, 編碼參數(指定編碼) 
     */  
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,  
            String cookieValue, int cookieMaxage, String encodeString) {  
        doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);  
    }  
  
    /** 
     * 刪除Cookie帶cookie域名 
     */  
    public static void deleteCookie(HttpServletRequest request, HttpServletResponse response,  
            String cookieName) {  
        doSetCookie(request, response, cookieName, "", -1, false);  
    }  
  
    /** 
     * 設置Cookie的值,並使其在指定時間內生效 
     *  
     * @param cookieMaxage cookie生效的最大秒數 
     */  
    private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,  
            String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {  
        try {  
            if (cookieValue == null) {  
                cookieValue = "";  
            } else if (isEncode) {  
                cookieValue = URLEncoder.encode(cookieValue, "utf-8");  
            }  
            Cookie cookie = new Cookie(cookieName, cookieValue);  
            if (cookieMaxage > 0)  
                cookie.setMaxAge(cookieMaxage);  
            if (null != request) {// 設置域名的cookie  
                String domainName = getDomainName(request);  
                System.out.println(domainName);  
                if (!"localhost".equals(domainName)) {  
                    cookie.setDomain(domainName);  
                }  
            }  
            cookie.setPath("/");  
            response.addCookie(cookie);  
        } catch (Exception e) {  
             e.printStackTrace();  
        }  
    }  
  
    /** 
     * 設置Cookie的值,並使其在指定時間內生效 
     *  
     * @param cookieMaxage cookie生效的最大秒數 
     */  
    private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,  
            String cookieName, String cookieValue, int cookieMaxage, String encodeString) {  
        try {  
            if (cookieValue == null) {  
                cookieValue = "";  
            } else {  
                cookieValue = URLEncoder.encode(cookieValue, encodeString);  
            }  
            Cookie cookie = new Cookie(cookieName, cookieValue);  
            if (cookieMaxage > 0)  
                cookie.setMaxAge(cookieMaxage);  
            if (null != request) {// 設置域名的cookie  
                String domainName = getDomainName(request);  
                System.out.println(domainName);  
                if (!"localhost".equals(domainName)) {  
                    cookie.setDomain(domainName);  
                }  
            }  
            cookie.setPath("/");  
            response.addCookie(cookie);  
        } catch (Exception e) {  
             e.printStackTrace();  
        }  
    }  
  
    /** 
     * 獲得cookie的域名 
     */  
    private static final String getDomainName(HttpServletRequest request) {  
        String domainName = null;  
  
        String serverName = request.getRequestURL().toString();  
        if (serverName == null || serverName.equals("")) {  
            domainName = "";  
        } else {  
            serverName = serverName.toLowerCase();  
            serverName = serverName.substring(7);  
            final int end = serverName.indexOf("/");  
            serverName = serverName.substring(0, end);  
            final String[] domains = serverName.split("\\.");  
            int len = domains.length;  
            if (len > 3) {  
                // www.xxx.com.cn  
                domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];  
            } else if (len <= 3 && len > 1) {  
                // xxx.com or xxx.cn  
                domainName = "." + domains[len - 2] + "." + domains[len - 1];  
            } else {  
                domainName = serverName;  
            }  
        }  
  
        if (domainName != null && domainName.indexOf(":") > 0) {  
            String[] ary = domainName.split("\\:");  
            domainName = ary[0];  
        }  
        return domainName;  
    }  
  
}

3.HttpClientUtil 相關包及文檔下載

[java] view plain copy
package com.taotao.utils;  
  
import java.io.IOException;  
import java.net.URI;  
import java.util.ArrayList;  
import java.util.List;  
import java.util.Map;  
  
import org.apache.http.NameValuePair;  
import org.apache.http.client.entity.UrlEncodedFormEntity;  
import org.apache.http.client.methods.CloseableHttpResponse;  
import org.apache.http.client.methods.HttpGet;  
import org.apache.http.client.methods.HttpPost;  
import org.apache.http.client.utils.URIBuilder;  
import org.apache.http.entity.ContentType;  
import org.apache.http.entity.StringEntity;  
import org.apache.http.impl.client.CloseableHttpClient;  
import org.apache.http.impl.client.HttpClients;  
import org.apache.http.message.BasicNameValuePair;  
import org.apache.http.util.EntityUtils;  
  
public class HttpClientUtil {  
  
    public static String doGet(String url, Map<String, String> param) {  
  
        // 建立Httpclient對象  
        CloseableHttpClient httpclient = HttpClients.createDefault();  
  
        String resultString = "";  
        CloseableHttpResponse response = null;  
        try {  
            // 建立uri  
            URIBuilder builder = new URIBuilder(url);  
            if (param != null) {  
                for (String key : param.keySet()) {  
                    builder.addParameter(key, param.get(key));  
                }  
            }  
            URI uri = builder.build();  
  
            // 建立http GET請求  
            HttpGet httpGet = new HttpGet(uri);  
  
            // 執行請求  
            response = httpclient.execute(httpGet);  
            // 判斷返回狀態是否爲200  
            if (response.getStatusLine().getStatusCode() == 200) {  
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                if (response != null) {  
                    response.close();  
                }  
                httpclient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return resultString;  
    }  
  
    public static String doGet(String url) {  
        return doGet(url, null);  
    }  
  
    public static String doPost(String url, Map<String, String> param) {  
        // 建立Httpclient對象  
        CloseableHttpClient httpClient = HttpClients.createDefault();  
        CloseableHttpResponse response = null;  
        String resultString = "";  
        try {  
            // 建立Http Post請求  
            HttpPost httpPost = new HttpPost(url);  
            // 建立參數列表  
            if (param != null) {  
                List<NameValuePair> paramList = new ArrayList<>();  
                for (String key : param.keySet()) {  
                    paramList.add(new BasicNameValuePair(key, param.get(key)));  
                }  
                // 模擬表單  
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);  
                httpPost.setEntity(entity);  
            }  
            // 執行http請求  
            response = httpClient.execute(httpPost);  
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                response.close();  
            } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
        }  
  
        return resultString;  
    }  
  
    public static String doPost(String url) {  
        return doPost(url, null);  
    }  
      
    public static String doPostJson(String url, String json) {  
        // 建立Httpclient對象  
        CloseableHttpClient httpClient = HttpClients.createDefault();  
        CloseableHttpResponse response = null;  
        String resultString = "";  
        try {  
            // 建立Http Post請求  
            HttpPost httpPost = new HttpPost(url);  
            // 建立請求內容  
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);  
            httpPost.setEntity(entity);  
            // 執行http請求  
            response = httpClient.execute(httpPost);  
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                response.close();  
            } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
        }  
  
        return resultString;  
    }  
}

4.FastDFSClient工具類

import org.csource.common.NameValuePair;  
import org.csource.fastdfs.ClientGlobal;  
import org.csource.fastdfs.StorageClient1;  
import org.csource.fastdfs.StorageServer;  
import org.csource.fastdfs.TrackerClient;  
import org.csource.fastdfs.TrackerServer;  
  
public class FastDFSClient {  
  
    private TrackerClient trackerClient = null;  
    private TrackerServer trackerServer = null;  
    private StorageServer storageServer = null;  
    private StorageClient1 storageClient = null;  
      
    public FastDFSClient(String conf) throws Exception {  
        if (conf.contains("classpath:")) {  
            conf = conf.replace("classpath:", this.getClass().getResource("/").getPath());  
        }  
        ClientGlobal.init(conf);  
        trackerClient = new TrackerClient();  
        trackerServer = trackerClient.getConnection();  
        storageServer = null;  
        storageClient = new StorageClient1(trackerServer, storageServer);  
    }  
      
    /** 
     * 上傳文件方法 
     * <p>Title: uploadFile</p> 
     * <p>Description: </p> 
     * @param fileName 文件全路徑 
     * @param extName 文件擴展名,不包含(.) 
     * @param metas 文件擴展信息 
     * @return 
     * @throws Exception 
     */  
    public String uploadFile(String fileName, String extName, NameValuePair[] metas) throws Exception {  
        String result = storageClient.upload_file1(fileName, extName, metas);  
        return result;  
    }  
      
    public String uploadFile(String fileName) throws Exception {  
        return uploadFile(fileName, null, null);  
    }  
      
    public String uploadFile(String fileName, String extName) throws Exception {  
        return uploadFile(fileName, extName, null);  
    }  
      
    /** 
     * 上傳文件方法 
     * <p>Title: uploadFile</p> 
     * <p>Description: </p> 
     * @param fileContent 文件的內容,字節數組 
     * @param extName 文件擴展名 
     * @param metas 文件擴展信息 
     * @return 
     * @throws Exception 
     */  
    public String uploadFile(byte[] fileContent, String extName, NameValuePair[] metas) throws Exception {  
          
        String result = storageClient.upload_file1(fileContent, extName, metas);  
        return result;  
    }  
      
    public String uploadFile(byte[] fileContent) throws Exception {  
        return uploadFile(fileContent, null, null);  
    }  
      
    public String uploadFile(byte[] fileContent, String extName) throws Exception {  
        return uploadFile(fileContent, extName, null);  
    }  
}  
[java] view plain copy
<span style="font-size:14px;font-weight:normal;">public class FastDFSTest {  
  
    @Test  
    public void testFileUpload() throws Exception {  
        // 一、加載配置文件,配置文件中的內容就是tracker服務的地址。  
        ClientGlobal.init("D:/workspaces-itcast/term197/taotao-manager-web/src/main/resources/resource/client.conf");  
        // 二、建立一個TrackerClient對象。直接new一個。  
        TrackerClient trackerClient = new TrackerClient();  
        // 三、使用TrackerClient對象建立鏈接,得到一個TrackerServer對象。  
        TrackerServer trackerServer = trackerClient.getConnection();  
        // 四、建立一個StorageServer的引用,值爲null  
        StorageServer storageServer = null;  
        // 五、建立一個StorageClient對象,須要兩個參數TrackerServer對象、StorageServer的引用  
        StorageClient storageClient = new StorageClient(trackerServer, storageServer);  
        // 六、使用StorageClient對象上傳圖片。  
        //擴展名不帶「.」  
        String[] strings = storageClient.upload_file("D:/Documents/Pictures/images/200811281555127886.jpg", "jpg", null);  
        // 七、返回數組。包含組名和圖片的路徑。  
        for (String string : strings) {  
            System.out.println(string);  
        }  
    }  
}</span>

5.獲取異常的堆棧信息

[java] view plain copy
package com.taotao.utils;  
  
import java.io.PrintWriter;  
import java.io.StringWriter;  
  
public class ExceptionUtil {  
  
    /** 
     * 獲取異常的堆棧信息 
     *  
     * @param t 
     * @return 
     */  
    public static String getStackTrace(Throwable t) {  
        StringWriter sw = new StringWriter();  
        PrintWriter pw = new PrintWriter(sw);  
  
        try {  
            t.printStackTrace(pw);  
            return sw.toString();  
        } finally {  
            pw.close();  
        }  
    }  
}  

6.easyUIDataGrid對象返回值
[java] view plain copy
package com.taotao.result;  
  
import java.util.List;  
  
/** 
 * easyUIDataGrid對象返回值 
 * <p>Title: EasyUIResult</p> 
 * <p>Description: </p> 
 * <p>Company: www.itcast.com</p>  
 * @author  入雲龍 
 * @date    2015年7月21日下午4:12:52 
 * @version 1.0 
 */  
public class EasyUIResult {  
  
    private Integer total;  
      
    private List<?> rows;  
      
    public EasyUIResult(Integer total, List<?> rows) {  
        this.total = total;  
        this.rows = rows;  
    }  
      
    public EasyUIResult(long total, List<?> rows) {  
        this.total = (int) total;  
        this.rows = rows;  
    }  
  
    public Integer getTotal() {  
        return total;  
    }  
    public void setTotal(Integer total) {  
        this.total = total;  
    }  
    public List<?> getRows() {  
        return rows;  
    }  
    public void setRows(List<?> rows) {  
        this.rows = rows;  
    }  
      
      
}

7.ftp上傳下載工具類

[java] view plain copy
package com.taotao.utils;  
  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStream;  
  
import org.apache.commons.net.ftp.FTP;  
import org.apache.commons.net.ftp.FTPClient;  
import org.apache.commons.net.ftp.FTPFile;  
import org.apache.commons.net.ftp.FTPReply;  
  
/** 
 * ftp上傳下載工具類 
 * <p>Title: FtpUtil</p> 
 * <p>Description: </p> 
 * <p>Company: www.itcast.com</p>  
 * @author  入雲龍 
 * @date    2015年7月29日下午8:11:51 
 * @version 1.0 
 */  
public class FtpUtil {  
  
    /**  
     * Description: 向FTP服務器上傳文件  
     * @param host FTP服務器hostname  
     * @param port FTP服務器端口  
     * @param username FTP登陸帳號  
     * @param password FTP登陸密碼  
     * @param basePath FTP服務器基礎目錄 
     * @param filePath FTP服務器文件存放路徑。例如分日期存放:/2015/01/01。文件的路徑爲basePath+filePath 
     * @param filename 上傳到FTP服務器上的文件名  
     * @param input 輸入流  
     * @return 成功返回true,不然返回false  
     */    
    public static boolean uploadFile(String host, int port, String username, String password, String basePath,  
            String filePath, String filename, InputStream input) {  
        boolean result = false;  
        FTPClient ftp = new FTPClient();  
        try {  
            int reply;  
            ftp.connect(host, port);// 鏈接FTP服務器  
            // 若是採用默認端口,可使用ftp.connect(host)的方式直接鏈接FTP服務器  
            ftp.login(username, password);// 登陸  
            reply = ftp.getReplyCode();  
            if (!FTPReply.isPositiveCompletion(reply)) {  
                ftp.disconnect();  
                return result;  
            }  
            //切換到上傳目錄  
            if (!ftp.changeWorkingDirectory(basePath+filePath)) {  
                //若是目錄不存在建立目錄  
                String[] dirs = filePath.split("/");  
                String tempPath = basePath;  
                for (String dir : dirs) {  
                    if (null == dir || "".equals(dir)) continue;  
                    tempPath += "/" + dir;  
                    if (!ftp.changeWorkingDirectory(tempPath)) {  
                        if (!ftp.makeDirectory(tempPath)) {  
                            return result;  
                        } else {  
                            ftp.changeWorkingDirectory(tempPath);  
                        }  
                    }  
                }  
            }  
            //設置上傳文件的類型爲二進制類型  
            ftp.setFileType(FTP.BINARY_FILE_TYPE);  
            //上傳文件  
            if (!ftp.storeFile(filename, input)) {  
                return result;  
            }  
            input.close();  
            ftp.logout();  
            result = true;  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            if (ftp.isConnected()) {  
                try {  
                    ftp.disconnect();  
                } catch (IOException ioe) {  
                }  
            }  
        }  
        return result;  
    }  
      
    /**  
     * Description: 從FTP服務器下載文件  
     * @param host FTP服務器hostname  
     * @param port FTP服務器端口  
     * @param username FTP登陸帳號  
     * @param password FTP登陸密碼  
     * @param remotePath FTP服務器上的相對路徑  
     * @param fileName 要下載的文件名  
     * @param localPath 下載後保存到本地的路徑  
     * @return  
     */    
    public static boolean downloadFile(String host, int port, String username, String password, String remotePath,  
            String fileName, String localPath) {  
        boolean result = false;  
        FTPClient ftp = new FTPClient();  
        try {  
            int reply;  
            ftp.connect(host, port);  
            // 若是採用默認端口,可使用ftp.connect(host)的方式直接鏈接FTP服務器  
            ftp.login(username, password);// 登陸  
            reply = ftp.getReplyCode();  
            if (!FTPReply.isPositiveCompletion(reply)) {  
                ftp.disconnect();  
                return result;  
            }  
            ftp.changeWorkingDirectory(remotePath);// 轉移到FTP服務器目錄  
            FTPFile[] fs = ftp.listFiles();  
            for (FTPFile ff : fs) {  
                if (ff.getName().equals(fileName)) {  
                    File localFile = new File(localPath + "/" + ff.getName());  
  
                    OutputStream is = new FileOutputStream(localFile);  
                    ftp.retrieveFile(ff.getName(), is);  
                    is.close();  
                }  
            }  
  
            ftp.logout();  
            result = true;  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            if (ftp.isConnected()) {  
                try {  
                    ftp.disconnect();  
                } catch (IOException ioe) {  
                }  
            }  
        }  
        return result;  
    }  
      
    public static void main(String[] args) {  
        try {    
            FileInputStream in=new FileInputStream(new File("D:\\temp\\image\\gaigeming.jpg"));    
            boolean flag = uploadFile("192.168.25.133", 21, "ftpuser", "ftpuser", "/home/ftpuser/www/images","/2015/01/21", "gaigeming.jpg", in);    
            System.out.println(flag);    
        } catch (FileNotFoundException e) {    
            e.printStackTrace();    
        }    
    }  
}

8.各類id生成策略

[java] view plain copy
package com.taotao.utils;  
  
import java.util.Random;  
  
/** 
 * 各類id生成策略 
 * <p>Title: IDUtils</p> 
 * <p>Description: </p> 
 * @date    2015年7月22日下午2:32:10 
 * @version 1.0 
 */  
public class IDUtils {  
  
    /** 
     * 圖片名生成 
     */  
    public static String genImageName() {  
        //取當前時間的長整形值包含毫秒  
        long millis = System.currentTimeMillis();  
        //long millis = System.nanoTime();  
        //加上三位隨機數  
        Random random = new Random();  
        int end3 = random.nextInt(999);  
        //若是不足三位前面補0  
        String str = millis + String.format("%03d", end3);  
          
        return str;  
    }  
      
    /** 
     * 商品id生成 
     */  
    public static long genItemId() {  
        //取當前時間的長整形值包含毫秒  
        long millis = System.currentTimeMillis();  
        //long millis = System.nanoTime();  
        //加上兩位隨機數  
        Random random = new Random();  
        int end2 = random.nextInt(99);  
        //若是不足兩位前面補0  
        String str = millis + String.format("%02d", end2);  
        long id = new Long(str);  
        return id;  
    }  
      
    public static void main(String[] args) {  
        for(int i=0;i< 100;i++)  
        System.out.println(genItemId());  
    }  
}

9.上傳圖片返回值

[java] view plain copy
package com.result;web

/** 
 * 上傳圖片返回值 
 * <p>Title: PictureResult</p> 
 * <p>Description: </p> 
 * <p>Company: www.itcast.com</p>  
 * @author  入雲龍 
 * @date    2015年7月22日下午2:09:02 
 * @version 1.0 
 */  
public class PictureResult {  
  
    /** 
     * 上傳圖片返回值,成功:0 失敗:1     
     */  
    private Integer error;  
    /** 
     * 回顯圖片使用的url 
     */  
    private String url;  
    /** 
     * 錯誤時的錯誤消息 
     */  
    private String message;  
    public PictureResult(Integer state, String url) {  
        this.url = url;  
        this.error = state;  
    }  
    public PictureResult(Integer state, String url, String errorMessage) {  
        this.url = url;  
        this.error = state;  
        this.message = errorMessage;  
    }  
    public Integer getError() {  
        return error;  
    }  
    public void setError(Integer error) {  
        this.error = error;  
    }  
    public String getUrl() {  
        return url;  
    }  
    public void setUrl(String url) {  
        this.url = url;  
    }  
    public String getMessage() {  
        return message;  
    }  
    public void setMessage(String message) {  
        this.message = message;  
    }  
      
}

10.自定義響應結構

[java] view plain copy
package com.result;  
  
import java.util.List;  
  
import com.fasterxml.jackson.databind.JsonNode;  
import com.fasterxml.jackson.databind.ObjectMapper;  
  
/** 
 * 自定義響應結構 
 */  
public class TaotaoResult {  
  
    // 定義jackson對象  
    private static final ObjectMapper MAPPER = new ObjectMapper();  
  
    // 響應業務狀態  
    private Integer status;  
  
    // 響應消息  
    private String msg;  
  
    // 響應中的數據  
    private Object data;  
  
    public static TaotaoResult build(Integer status, String msg, Object data) {  
        return new TaotaoResult(status, msg, data);  
    }  
  
    public static TaotaoResult ok(Object data) {  
        return new TaotaoResult(data);  
    }  
  
    public static TaotaoResult ok() {  
        return new TaotaoResult(null);  
    }  
  
    public TaotaoResult() {  
  
    }  
  
    public static TaotaoResult build(Integer status, String msg) {  
        return new TaotaoResult(status, msg, null);  
    }  
  
    public TaotaoResult(Integer status, String msg, Object data) {  
        this.status = status;  
        this.msg = msg;  
        this.data = data;  
    }  
  
    public TaotaoResult(Object data) {  
        this.status = 200;  
        this.msg = "OK";  
        this.data = data;  
    }  
  
//    public Boolean isOK() {  
//        return this.status == 200;  
//    }  
  
    public Integer getStatus() {  
        return status;  
    }  
  
    public void setStatus(Integer status) {  
        this.status = status;  
    }  
  
    public String getMsg() {  
        return msg;  
    }  
  
    public void setMsg(String msg) {  
        this.msg = msg;  
    }  
  
    public Object getData() {  
        return data;  
    }  
  
    public void setData(Object data) {  
        this.data = data;  
    }  
  
    /** 
     * 將json結果集轉化爲TaotaoResult對象 
     *  
     * @param jsonData json數據 
     * @param clazz TaotaoResult中的object類型 
     * @return 
     */  
    public static TaotaoResult formatToPojo(String jsonData, Class<?> clazz) {  
        try {  
            if (clazz == null) {  
                return MAPPER.readValue(jsonData, TaotaoResult.class);  
            }  
            JsonNode jsonNode = MAPPER.readTree(jsonData);  
            JsonNode data = jsonNode.get("data");  
            Object obj = null;  
            if (clazz != null) {  
                if (data.isObject()) {  
                    obj = MAPPER.readValue(data.traverse(), clazz);  
                } else if (data.isTextual()) {  
                    obj = MAPPER.readValue(data.asText(), clazz);  
                }  
            }  
            return build(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj);  
        } catch (Exception e) {  
            return null;  
        }  
    }  
  
    /** 
     * 沒有object對象的轉化 
     *  
     * @param json 
     * @return 
     */  
    public static TaotaoResult format(String json) {  
        try {  
            return MAPPER.readValue(json, TaotaoResult.class);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return null;  
    }  
  
    /** 
     * Object是集合轉化 
     *  
     * @param jsonData json數據 
     * @param clazz 集合中的類型 
     * @return 
     */  
    public static TaotaoResult formatToList(String jsonData, Class<?> clazz) {  
        try {  
            JsonNode jsonNode = MAPPER.readTree(jsonData);  
            JsonNode data = jsonNode.get("data");  
            Object obj = null;  
            if (data.isArray() && data.size() > 0) {  
                obj = MAPPER.readValue(data.traverse(),  
                        MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));  
            }  
            return build(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj);  
        } catch (Exception e) {  
            return null;  
        }  
    }  
  
}

11.jedis操做

[java] view plain copy
package com.taotao.jedis;  
  
public interface JedisClient {  
  
    String set(String key, String value);  
    String get(String key);  
    Boolean exists(String key);  
    Long expire(String key, int seconds);  
    Long ttl(String key);  
    Long incr(String key);  
    Long hset(String key, String field, String value);  
    String hget(String key, String field);  
    Long hdel(String key, String... field);  
}  
[java] view plain copy
package com.taotao.jedis;  
  
import org.springframework.beans.factory.annotation.Autowired;  
  
import redis.clients.jedis.JedisCluster;  
  
public class JedisClientCluster implements JedisClient {  
      
    @Autowired  
    private JedisCluster jedisCluster;  
  
    @Override  
    public String set(String key, String value) {  
        return jedisCluster.set(key, value);  
    }  
  
    @Override  
    public String get(String key) {  
        return jedisCluster.get(key);  
    }  
  
    @Override  
    public Boolean exists(String key) {  
        return jedisCluster.exists(key);  
    }  
  
    @Override  
    public Long expire(String key, int seconds) {  
        return jedisCluster.expire(key, seconds);  
    }  
  
    @Override  
    public Long ttl(String key) {  
        return jedisCluster.ttl(key);  
    }  
  
    @Override  
    public Long incr(String key) {  
        return jedisCluster.incr(key);  
    }  
  
    @Override  
    public Long hset(String key, String field, String value) {  
        return jedisCluster.hset(key, field, value);  
    }  
  
    @Override  
    public String hget(String key, String field) {  
        return jedisCluster.hget(key, field);  
    }  
  
    @Override  
    public Long hdel(String key, String... field) {  
        return jedisCluster.hdel(key, field);  
    }  
  
}  
[java] view plain copy
package com.taotao.jedis;  
  
  
import org.springframework.beans.factory.annotation.Autowired;  
  
  
import redis.clients.jedis.Jedis;  
import redis.clients.jedis.JedisPool;  
  
  
public class JedisClientPool implements JedisClient {  
      
    @Autowired  
    private JedisPool jedisPool;  
  
  
    @Override  
    public String set(String key, String value) {  
        Jedis jedis = jedisPool.getResource();  
        String result = jedis.set(key, value);  
        jedis.close();  
        return result;  
    }  
  
  
    @Override  
    public String get(String key) {  
        Jedis jedis = jedisPool.getResource();  
        String result = jedis.get(key);  
        jedis.close();  
        return result;  
    }  
  
  
    @Override  
    public Boolean exists(String key) {  
        Jedis jedis = jedisPool.getResource();  
        Boolean result = jedis.exists(key);  
        jedis.close();  
        return result;  
    }  
  
  
    @Override  
    public Long expire(String key, int seconds) {  
        Jedis jedis = jedisPool.getResource();  
        Long result = jedis.expire(key, seconds);  
        jedis.close();  
        return result;  
    }  
  
  
    @Override  
    public Long ttl(String key) {  
        Jedis jedis = jedisPool.getResource();  
        Long result = jedis.ttl(key);  
        jedis.close();  
        return result;  
    }  
  
  
    @Override  
    public Long incr(String key) {  
        Jedis jedis = jedisPool.getResource();  
        Long result = jedis.incr(key);  
        jedis.close();  
        return result;  
    }  
  
  
    @Override  
    public Long hset(String key, String field, String value) {  
        Jedis jedis = jedisPool.getResource();  
        Long result = jedis.hset(key, field, value);  
        jedis.close();  
        return result;  
    }  
  
  
    @Override  
    public String hget(String key, String field) {  
        Jedis jedis = jedisPool.getResource();  
        String result = jedis.hget(key, field);  
        jedis.close();  
        return result;  
    }  
  
  
    @Override  
    public Long hdel(String key, String... field) {  
        Jedis jedis = jedisPool.getResource();  
        Long result = jedis.hdel(key, field);  
        jedis.close();  
        return result;  
    }  
  
  
}

本文做者:[一個小迷糊]redis

閱讀原文spring

本文爲雲棲社區原創內容,未經容許不得轉載。apache

相關文章
相關標籤/搜索