• 封装的方法


    1.XmlUtil:Xml的操作类

    /**
         * 读取xml文档方法
         * @return
         */
        public static Document getDocument(){
            try {
                Document doc = new SAXReader().read(new File("e:/contact.xml"));
                return doc;
            } catch (DocumentException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        
    
        /**
         * 写出到xml文档中
         */
        public static void write2xml(Document doc){
            try {
                FileOutputStream out = new FileOutputStream("e:/contact.xml");
                OutputFormat format = OutputFormat.createPrettyPrint();
                format.setEncoding("utf-8");
                XMLWriter writer = new XMLWriter(out,format);
                writer.write(doc);
                writer.close();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    View Code

    2.jdbcUtil:对数据库的连接关闭操作

    /**
         * 抽取获取连接对象的方法
         */
        public static Connection getConnection(){
            try {
                Connection conn = DriverManager.getConnection(url, user, password);
                return conn;
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        
        
        /**
         * 释放资源的方法
         */
        public static void close(Connection conn,Statement stmt){
            if(stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }
        
        public static void close(Connection conn,Statement stmt,ResultSet rs){
            if(rs!=null)
                try {
                    rs.close();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                    throw new RuntimeException(e1);
                }
            if(stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
    View Code

     3.BaseDao:通用的数据操作类,我们自己写的可以继承他

    /**
     * 通用的dao,自己写的所有的dao都继承此类;
     * 此类定义了2个通用的方法:
     *     1. 更新
     *  2. 查询
     * @author Jie.Yuan
     *
     */
    public class BaseDao {
        
        // 初始化参数
        private Connection con;
        private PreparedStatement pstmt;
        private ResultSet rs;
    
        /**
         * 更新的通用方法
         * @param sql   更新的sql语句(update/insert/delete)
         * @param paramsValue  sql语句中占位符对应的值(如果没有占位符,传入null)
         */
        public void update(String sql,Object[] paramsValue){
            
            try {
                // 获取连接
                con = JdbcUtil.getConnection();
                // 创建执行命令的stmt对象
                pstmt = con.prepareStatement(sql);
                // 参数元数据: 得到占位符参数的个数
                int count = pstmt.getParameterMetaData().getParameterCount();
                
                // 设置占位符参数的值
                if (paramsValue != null && paramsValue.length > 0) {
                    // 循环给参数赋值
                    for(int i=0;i<count;i++) {
                        pstmt.setObject(i+1, paramsValue[i]);
                    }
                }
                // 执行更新
                pstmt.executeUpdate();
                
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                JdbcUtil.closeAll(con, pstmt, null);
            }
        }
        
        /**
         * 查询的通用方法
         * @param sql
         * @param paramsValue
         */
        public <T> List<T> query(String sql, Object[] paramsValue,Class<T> clazz){
            
            try {
                // 返回的集合
                List<T> list = new ArrayList<T>();
                // 对象
                T t = null;
                
                // 1. 获取连接
                con = JdbcUtil.getConnection();
                // 2. 创建stmt对象
                pstmt = con.prepareStatement(sql);
                // 3. 获取占位符参数的个数, 并设置每个参数的值
                int count = pstmt.getParameterMetaData().getParameterCount();
                if (paramsValue != null && paramsValue.length > 0) {
                    for (int i=0; i<paramsValue.length; i++) {
                        pstmt.setObject(i+1, paramsValue[i]);
                    }
                }
                // 4. 执行查询
                rs = pstmt.executeQuery();
                // 5. 获取结果集元数据
                ResultSetMetaData rsmd = rs.getMetaData();
                // ---> 获取列的个数
                int columnCount = rsmd.getColumnCount();
                
                // 6. 遍历rs
                while (rs.next()) {
                    // 要封装的对象
                    t = clazz.newInstance();
                    
                    // 7. 遍历每一行的每一列, 封装数据
                    for (int i=0; i<columnCount; i++) {
                        // 获取每一列的列名称
                        String columnName = rsmd.getColumnName(i + 1);
                        // 获取每一列的列名称, 对应的值
                        Object value = rs.getObject(columnName);
                        // 封装: 设置到t对象的属性中  【BeanUtils组件】
                        BeanUtils.copyProperty(t, columnName, value);                
                    }
                    
                    // 把封装完毕的对象,添加到list集合中
                    list.add(t);
                }
                
                return list;
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                JdbcUtil.closeAll(con, pstmt, rs);
            }
        }
    }
    View Code

     4.java后台获得html 的get请求结果

    // 构造HttpClient的实例
    HttpClient httpClient = new HttpClient();
    // 创建GET方法的实例
    GetMethod getMethod = new GetMethod(url);
    // 使用系统提供的默认的恢复策略 不重试       getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(TIME_OUT);
     // 执行getMethod
    int statusCode = httpClient.executeMethod(getMethod);
    if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + getMethod.getStatusLine());
                }
    // 处理内容
    String html = getMethod.getResponseBodyAsString();
    JSONObject jsonObject = JSONObject.parseObject(html);
    View Code

     5.HttpUtil工具类

    package com.ty.tyzxtj.util;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;
    
    import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpStatus;
    import org.apache.commons.httpclient.methods.GetMethod;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.commons.httpclient.params.HttpMethodParams;
    
    /**
     * http工具类
     * @author wangjiping
     *
     */
    public class HttpUtil {
        // 超时时间
        public static final int TIME_OUT = 50000;
        public static String post(String postUrl){
            String response = "";
            PostMethod postMethod = new PostMethod(postUrl);
            try {
                HttpClient client = new HttpClient();
                client.getHttpConnectionManager().getParams()
                        .setConnectionTimeout(50000);// 设置连接时间
                int status = client.executeMethod(postMethod);
                if (status == HttpStatus.SC_OK) {
                    InputStream inputStream = postMethod.getResponseBodyAsStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(
                            inputStream));
                    StringBuffer stringBuffer = new StringBuffer();
                    String str = "";
                    while ((str = br.readLine()) != null) {
                        stringBuffer.append(str);
                    }
                    response = stringBuffer.toString();
                } else {
                    response = "fail";
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 释放连接
                postMethod.releaseConnection();
            }
            return response;
        }
        public static String loadJson (String url) {  
            StringBuilder json = new StringBuilder();  
            try {  
                URL urlObject = new URL(url);  
                URLConnection uc = urlObject.openConnection();  
                BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));  
                String inputLine = null;  
                while ( (inputLine = in.readLine()) != null) {  
                    json.append(inputLine);  
                }  
                in.close();  
            } catch (MalformedURLException e) {  
                e.printStackTrace();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
            return json.toString();  
        } 
        public static String get(String url){
            String html = "";
            // 构造HttpClient的实例
            HttpClient httpClient = new HttpClient();
            // 创建GET方法的实例
            GetMethod getMethod = new GetMethod(url);
            // 使用系统提供的默认的恢复策略 不重试
            getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
            getMethod.setRequestHeader("Connection" , "Keep-Alive");
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(TIME_OUT);
            httpClient.getHttpConnectionManager().getParams().setSoTimeout(TIME_OUT);
            try {
                // 执行getMethod
                int statusCode = httpClient.executeMethod(getMethod);
                if (statusCode != HttpStatus.SC_OK) {
                    System.err.println("Method failed: " + getMethod.getStatusLine());
                }
                // 处理内容
                html = getMethod.getResponseBodyAsString();
            } catch (Exception e) {
            } finally {
                // 释放连接
                getMethod.releaseConnection();
            }
            return html;
        }
    }
    View Code

     使用实例:上传文件到指定服务器中去

        /**
         * 将微信图片保存到服务器-ftp形式
         * 
         * @param accessToken
         * @param mediaId
         * @param picPath
         * @throws Exception
         */
        public boolean saveImageToDisk1(String accessToken, String mediaId, String picPath, String id, String orderNo)
                throws Exception {
            boolean success = false;
            InputStream inputStream = getInputStream(accessToken, mediaId);
            String url = "121.43.123.123";//ftp.getUrl();
            int port = 32;//ftp.getPort();
            String username = "to123t";//ftp.getUsername();
            String password = "A1239--";//ftp.getPassword();
            FTPClient ftp = new FTPClient();
            try {
                int reply;
                ftp.connect(url, port);// 连接FTP服务器
                ftp.login(username, password);// 登录
                ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
                reply = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    return success;
                }
                ftp.makeDirectory(picPath);
                ftp.changeWorkingDirectory(picPath);
                ftp.enterLocalPassiveMode();
                Integer number = ftp.listFiles(picPath).length+1;
                String filename =  "安装照片" + number + ".jpg";
                boolean storeFile = ftp.storeFile(new String(filename.getBytes("utf-8"), "iso-8859-1"), inputStream);
                log.info(mediaId + "下载结果:" + storeFile);
                if (storeFile) {
                    success = true;
                    wechatMapper.updatePicUrl(id, "/file/wx/" + orderNo + "/安装照片" + number + ".jpg");
                } else {
                    success = false;
                }
                inputStream.close();
                ftp.logout();
                
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (ftp.isConnected()) {
                    try {
                        ftp.disconnect();
                    } catch (IOException ioe) {
    
                    }
                }
            }
            return success;
        }
    View Code

     6.根据api获得文件流

        /**
         * 获取文件流
         * 
         * @param accessToken
         * @param mediaId
         * @return
         */
        public static InputStream getInputStreamByApi(String urlApi) {
            InputStream is = null;
            try {
                URL urlGet = new URL(url);
                HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
                http.setRequestMethod("GET"); // 必须是get方式请求
                http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                http.setDoOutput(true);
                http.setDoInput(true);
                System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
                System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
                http.connect();
                // 获取文件转化为byte流
                is = http.getInputStream();
    
            } catch (Exception e) {
                e.printStackTrace();
            }
            return is;
    
        }
    View Code

     7.操作excel表格

        /**
         * 内容导出excel
         */
        public void exportExcel(HttpServletRequest request, int fenye, HttpServletResponse response, String fn, List<Map<String, Object>> result, String[] cols, String[] matchs) {
            Workbook workbook = new HSSFWorkbook();  
            for (int m = 0; m <= result.size()/fenye; m++) {
                Sheet sheet = workbook.createSheet(""+(m+1)+""); 
                Row row = sheet.createRow(0);  
                for (int i = 0; i < cols.length; i++) {
                    row.createCell(i).setCellValue(cols[i]);  
                }
                int rowIndex= 1;
                for (int i = m*fenye; i < (m+1)*fenye; i++) {
                    if(i==result.size()){
                        break;
                    }
                    Map<String, Object> map = result.get(i);
                    row = sheet.createRow(rowIndex++);  
                    for (int j = 0; j < cols.length; j++) {
                        if(matchs[j].equals("distance")){
                            row.createCell(j).setCellValue(Double.parseDouble(StringUtil.nullReplace(map.get(matchs[j])))); 
                        }else if(matchs[j].equals("duration")){
                            row.createCell(j).setCellValue(formatDuration(String.valueOf((map.get("duration")))));    
                        }else if(matchs[j].equals("start_time")){
                            if(StringUtil.nullReplace(map.get("start_time")).length()!=0&&StringUtil.nullReplace(map.get("start_time")).matches("^[0-9]*$")){
                                row.createCell(j).setCellValue(sdf2.format(map.get("start_time")));
                            }else{
                                if(StringUtil.nullReplace(map.get("start_time")).length()==21){
                                    row.createCell(j).setCellValue(StringUtil.nullReplace(map.get("start_time")).substring(0,19));
                                }else{
                                    row.createCell(j).setCellValue(StringUtil.nullReplace(map.get("start_time")));
                                }
                            }
                        }else if(matchs[j].equals("end_time")){
                            if("32503651199000".equals(map.get("end_time").toString())){
                                row.createCell(j).setCellValue("");
                            }else{
                                row.createCell(j).setCellValue(sdf2.format(map.get("end_time")));
                            }
                        }else{
                            row.createCell(j).setCellValue(StringUtil.nullReplace(map.get(matchs[j])));  
                        }
                        
                    }
                }
            }
            try {
                OutputStream output=response.getOutputStream();
                response.reset();
                //response.setHeader("Content-disposition", "attachment; filename="+fn);
                response.setContentType("application/msexcel");    
                boolean isMSIE = isMSBrowser(request);
                if (isMSIE) {  
                    fn = URLEncoder.encode(fn, "UTF-8");  
                } else {  
                    fn = new String(fn.getBytes("GBK"), "ISO-8859-1");  
                }  
                fn = fn.replaceAll(":", "-");
                response.setHeader("Content-disposition", "attachment;filename="" + fn + """);  
                workbook.write(output);
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    View Code

     8.加密密码

    package com.ty.tyzxtj.util;
    
    import java.security.Key;
    import java.security.SecureRandom;
    
    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.PBEKeySpec;
    import javax.crypto.spec.PBEParameterSpec;
    /**
     * 使用方式String pwd = PasswordUtil.encrypt(userName, password, PasswordUtil.getStaticSalt());
     * @author wangjiping
     *
     */
    public class PasswordUtil {
    
        /**
         * JAVA6支持以下任意一种算法 PBEWITHMD5ANDDES PBEWITHMD5ANDTRIPLEDES
         * PBEWITHSHAANDDESEDE PBEWITHSHA1ANDRC2_40 PBKDF2WITHHMACSHA1
         * */
    
        /**
         * 定义使用的算法为:PBEWITHMD5andDES算法
         */
        public static final String ALGORITHM = "PBEWithMD5AndDES";//加密算法
        public static final String Salt = "63293188";//密钥
    
        /**
         * 定义迭代次数为1000次
         */
        private static final int ITERATIONCOUNT = 1000;
    
        /**
         * 获取加密算法中使用的盐值,解密中使用的盐值必须与加密中使用的相同才能完成操作. 盐长度必须为8字节
         * 
         * @return byte[] 盐值
         * */
        public static byte[] getSalt() throws Exception {
            // 实例化安全随机数
            SecureRandom random = new SecureRandom();
            // 产出盐
            return random.generateSeed(8);
        }
    
        public static byte[] getStaticSalt() {
            // 产出盐
            return Salt.getBytes();
        }
    
        /**
         * 根据PBE密码生成一把密钥
         * 
         * @param password
         *            生成密钥时所使用的密码
         * @return Key PBE算法密钥
         * */
        private static Key getPBEKey(String password) {
            // 实例化使用的算法
            SecretKeyFactory keyFactory;
            SecretKey secretKey = null;
            try {
                keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
                // 设置PBE密钥参数
                PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
                // 生成密钥
                secretKey = keyFactory.generateSecret(keySpec);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
            return secretKey;
        }
    
        /**
         * 加密明文字符串
         * 
         * @param plaintext
         *            待加密的明文字符串
         * @param password
         *            生成密钥时所使用的密码
         * @param salt
         *            盐值
         * @return 加密后的密文字符串
         * @throws Exception
         */
        public static String encrypt(String plaintext, String password, byte[] salt) {
    
            Key key = getPBEKey(password);
            byte[] encipheredData = null;
            PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, ITERATIONCOUNT);
            try {
                Cipher cipher = Cipher.getInstance(ALGORITHM);
    
                cipher.init(Cipher.ENCRYPT_MODE, key, parameterSpec);
    
                encipheredData = cipher.doFinal(plaintext.getBytes());
            } catch (Exception e) {
            }
            return bytesToHexString(encipheredData);
        }
    
        /**
         * 解密密文字符串
         * 
         * @param ciphertext
         *            待解密的密文字符串
         * @param password
         *            生成密钥时所使用的密码(如需解密,该参数需要与加密时使用的一致)
         * @param salt
         *            盐值(如需解密,该参数需要与加密时使用的一致)
         * @return 解密后的明文字符串
         * @throws Exception
         */
        public static String decrypt(String ciphertext, String password, byte[] salt) {
    
            Key key = getPBEKey(password);
            byte[] passDec = null;
            PBEParameterSpec parameterSpec = new PBEParameterSpec(getStaticSalt(), ITERATIONCOUNT);
            try {
                Cipher cipher = Cipher.getInstance(ALGORITHM);
    
                cipher.init(Cipher.DECRYPT_MODE, key, parameterSpec);
    
                passDec = cipher.doFinal(hexStringToBytes(ciphertext));
            }
    
            catch (Exception e) {
                // TODO: handle exception
            }
            return new String(passDec);
        }
    
        /**
         * 将字节数组转换为十六进制字符串
         * 
         * @param src
         *            字节数组
         * @return
         */
        public static String bytesToHexString(byte[] src) {
            StringBuilder stringBuilder = new StringBuilder("");
            if (src == null || src.length <= 0) {
                return null;
            }
            for (int i = 0; i < src.length; i++) {
                int v = src[i] & 0xFF;
                String hv = Integer.toHexString(v);
                if (hv.length() < 2) {
                    stringBuilder.append(0);
                }
                stringBuilder.append(hv);
            }
            return stringBuilder.toString();
        }
    
        /**
         * 将十六进制字符串转换为字节数组
         * 
         * @param hexString
         *            十六进制字符串
         * @return
         */
        public static byte[] hexStringToBytes(String hexString) {
            if (hexString == null || hexString.equals("")) {
                return null;
            }
            hexString = hexString.toUpperCase();
            int length = hexString.length() / 2;
            char[] hexChars = hexString.toCharArray();
            byte[] d = new byte[length];
            for (int i = 0; i < length; i++) {
                int pos = i * 2;
                d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
            }
            return d;
        }
    
        private static byte charToByte(char c) {
            return (byte) "0123456789ABCDEF".indexOf(c);
        }
    
    }
    View Code
  • 相关阅读:
    WPF 关于多语言 的实现 学习,利用反射中的特性
    WPF Textbox 中文输入崩溃 规避
    自定义控件.依赖项属性同步更新内部控件属性
    HexInput
    HashMap实现原理分析
    centos下nginx安装
    dos下mybatis自动生成代码
    设计模式之装饰器模式
    Java 中的悲观锁和乐观锁的实现
    redis分布式锁
  • 原文地址:https://www.cnblogs.com/xiaoping1993/p/6860381.html
Copyright © 2020-2023  润新知