常用工具类的积累

来源:互联网 发布:朝鲜族吃里扒外知乎 编辑:程序博客网 时间:2021/06/19 13:31

1.将XML转换为Map集合(下面的代码中request返回的就是xml)

public static Map<String, String> xmlToMap(HttpServletRequest request) throws IOException, DocumentException {        Map<String, String> map = new HashMap<String, String>();        SAXReader reader = new SAXReader();        InputStream input = request.getInputStream();        Document doc = reader.read(input);        Element root = doc.getRootElement();        List<Element> list = root.elements();        for (Element e : list) {            map.put(e.getName(), e.getText());        }        input.close();        return map;    }

以上代码使用到的jar包有:
这里写图片描述

2.将pojo类转换为XML格式的数据

student类:(pojo类)

package com.huihui.test3;public class Student {    private String name;    private int age;    private String sex;    private String birth;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public String getSex() {        return sex;    }    public void setSex(String sex) {        this.sex = sex;    }    public String getBirth() {        return birth;    }    public void setBirth(String birth) {        this.birth = birth;    }}

School类:(pojo类)

package com.huihui.test3;public class School {    private String schoolName;    private Student student;    public String getSchoolName() {        return schoolName;    }    public void setSchoolName(String schoolName) {        this.schoolName = schoolName;    }    public Student getStudent() {        return student;    }    public void setStudent(Student student) {        this.student = student;    }}

测试类:

package com.huihui.test3;import com.thoughtworks.xstream.XStream;public class Test {    public static void main(String[] args) {        Student student = new Student();        student.setName("张耀晖");        student.setAge(24);        student.setSex("男");        student.setBirth("1992-11-03");        School school = new School();        school.setSchoolName("南华大学");        school.setStudent(student);        XStream xstream = new XStream();        xstream.alias("xml", school.getClass());        String xmlstr = xstream.toXML(school);        System.out.println(xmlstr);    }}

以上代码所用到的jar包:
这里写图片描述
运行结果截图:
这里写图片描述

3.使用Get或者Post请求的方式请求一个URL(请求url后会返回json数据才可以)

Get请求方式:

public static JSONObject doGetStr(String url) {        DefaultHttpClient httpClient = new DefaultHttpClient();        HttpGet httpGet = new HttpGet(url);        JSONObject jsonObject = null;        try {            HttpResponse response = httpClient.execute(httpGet);// 接收请求后的返回的结果            HttpEntity entity = response.getEntity();            if (entity != null) {                String result = EntityUtils.toString(entity, "UTF-8");                jsonObject = JSONObject.fromObject(result);            }        } catch (ClientProtocolException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return jsonObject;    }

Post请求方式:

public static JSONObject doPostStr(String url, String outStr) {        DefaultHttpClient httpClient = new DefaultHttpClient();        HttpPost httpPost = new HttpPost(url);        JSONObject jsonObject = null;        try {            httpPost.setEntity(new StringEntity(outStr, "UTF-8"));            HttpResponse response = httpClient.execute(httpPost);            String result = EntityUtils.toString(response.getEntity(), "UTF-8");            jsonObject = JSONObject.fromObject(result);        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        } catch (ClientProtocolException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return jsonObject;    }

以上代码使用的jar包:
这里写图片描述
这里写图片描述

4.文件上传

public static String upload(String filePath, String accessToken, String type)            throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {        File file = new File(filePath);        if (!file.exists() || !file.isFile()) {            throw new IOException("文件不存在");        }        String url = UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);        URL urlObj = new URL(url);        // 连接        HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();        con.setRequestMethod("POST");        con.setDoInput(true);        con.setDoOutput(true);        con.setUseCaches(false);        // 设置请求头信息        con.setRequestProperty("Connection", "Keep-Alive");        con.setRequestProperty("Charset", "UTF-8");        // 设置边界        String BOUNDARY = "----------" + System.currentTimeMillis();        con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);        StringBuilder sb = new StringBuilder();        sb.append("--");        sb.append(BOUNDARY);        sb.append("\r\n");        sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");        sb.append("Content-Type:application/octet-stream\r\n\r\n");        byte[] head = sb.toString().getBytes("utf-8");        // 获得输出流        OutputStream out = new DataOutputStream(con.getOutputStream());        // 输出表头        out.write(head);         // 文件正文部分        // 把文件已流文件的方式 推入到url中        DataInputStream in = new DataInputStream(new FileInputStream(file));        int bytes = 0;        byte[] bufferOut = new byte[1024];        while ((bytes = in.read(bufferOut)) != -1) {            out.write(bufferOut, 0, bytes);        }        in.close();        // 结尾部分        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线        out.write(foot);        out.flush();        out.close();        StringBuffer buffer = new StringBuffer();        BufferedReader reader = null;        String result = null;        try {            // 定义BufferedReader输入流来读取URL的响应            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));            String line = null;            while ((line = reader.readLine()) != null) {                buffer.append(line);            }            if (result == null) {                result = buffer.toString();            }        } catch (IOException e) {            e.printStackTrace();        } finally {            if (reader != null) {                reader.close();            }        }        JSONObject jsonObj = JSONObject.fromObject(result);        System.out.println(jsonObj);        String typeName = "media_id";        if ("thumb".equals(type)) {            typeName = type + "_media_id";        }        String mediaId = jsonObj.getString(typeName);        return mediaId;    }

5.SHA1加密

//sha1加密    public static String getSha1(String str){        if(str==null||str.length()==0){            return null;        }        char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};        try {            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");            mdTemp.update(str.getBytes("UTF-8"));            byte[] md = mdTemp.digest();            int j = md.length;            char buf[] = new char[j*2];            int k = 0;            for (int i = 0; i < j; i++) {                byte byte0 = md[i];                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];                buf[k++] = hexDigits[byte0 & 0xf];            }            return new String(buf);        } catch (Exception e) {            return null;        }    }

6.MD5加密工具类:

package com.huihui.util;import java.security.MessageDigest;/** * MD5加密工具类 * @author Administrator * */public class Md5Util {    public final static String MD5(String s){        char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};         try {            byte[] strTemp = s.getBytes();            MessageDigest mdTemp = MessageDigest.getInstance("MD5");            mdTemp.update(strTemp);            byte[] md = mdTemp.digest();            int j = md.length;            char str[] = new char[j*2];            int k = 0;            for (int i = 0; i < j; i++) {                byte byte0 = md[i];                str[k++] = hexDigits[byte0>>>4&0xf];                str[k++] = hexDigits[byte0 & 0xf];            }            return new String(str);        } catch (Exception e) {            return null;        }    }    public static void main(String[] args) {        System.out.println(Md5Util.MD5("b"));    }}

7.SQL工具类:

package com.huihui.util;import java.io.FileInputStream;import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.util.ArrayList;import java.util.Properties;/** * 这是一个操作数据库的工具类 *  * @author Administrator *  */public class SqlHelper {    private static String DBDRIVER;    private static String DBURL;    private static String DBUSER;    private static String DBPASS;    // 定义需要的变量    private static Connection conn = null;    private static PreparedStatement pstmt = null;    private static ResultSet rs = null;    public static Connection getConn() {        return conn;    }    public static PreparedStatement getPstmt() {        return pstmt;    }    public static ResultSet getRs() {        return rs;    }    // 加载驱动,只需要加载一次    static {        FileInputStream fis = null;        try {            // 从dbinfo.properties文件中读取配置信息            Properties pp = new Properties();            fis = new FileInputStream(                    "E:\\myeclipse10code\\UserLoginUp\\dbinfo.properties");            pp.load(fis);            DBDRIVER = pp.getProperty("driver");            DBURL = pp.getProperty("url");            DBUSER = pp.getProperty("user");            DBPASS = pp.getProperty("pass");            Class.forName(DBDRIVER);        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                fis.close();            } catch (IOException e) {                e.printStackTrace();            }            fis = null;        }    }    // 得到连接    public static Connection getConnection() {        try {            conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);        } catch (SQLException e) {            e.printStackTrace();        }        return conn;    }    // 关闭资源    public static void close(ResultSet rs, PreparedStatement pstmt,            Connection conn) {        if (rs != null) {            try {                rs.close();            } catch (Exception e) {                e.printStackTrace();            } finally {                rs = null;            }        }        if (pstmt != null) {            try {                pstmt.close();            } catch (Exception e) {                e.printStackTrace();            } finally {                pstmt = null;            }        }        if (conn != null) {            try {                conn.close();            } catch (Exception e) {                e.printStackTrace();            } finally {                conn = null;            }        }    }    // 先写一个update/delete/insert    // sql格式: update 表名 set 字段名=? where 字段=?    public static void executeUpdate1(String sql, String[] parameters) {        try {            conn = getConnection();            pstmt = conn.prepareStatement(sql);            // 给?赋值            if (parameters != null) {                for (int i = 0; i < parameters.length; i++) {                    pstmt.setString(i + 1, parameters[i]);                }            }            // 执行            pstmt.executeUpdate();        } catch (Exception e) {            e.printStackTrace();            throw new RuntimeException(e.getMessage());        } finally {            close(rs, pstmt, conn);        }    }    // 如果有多个update/delete/insert语句【需要考虑事务】    public static void executeUpdate2(String[] sqls, String[][] parameters) {        try {            conn = getConnection();            // 因为这时用户传入的可能是多个sql语句            conn.setAutoCommit(false);            if (sqls != null) {                for (int i = 0; i < parameters.length; i++) {                    pstmt = conn.prepareStatement(sqls[i]);                    if (parameters[i] != null) {                        for (int j = 0; j < parameters[i].length; j++) {                            pstmt.setString(j + 1, parameters[i][j]);                        }                    }                    pstmt.executeUpdate();                }            }            conn.commit();        } catch (Exception e) {            // 回滚            try {                conn.rollback();            } catch (SQLException e1) {                e1.printStackTrace();            }            e.printStackTrace();            throw new RuntimeException(e.getMessage());        } finally {            close(rs, pstmt, conn);        }    }    // 统一的select    public static ResultSet executeQuery(String sql, String[] parameters) {        try {            conn = getConnection();            pstmt = conn.prepareStatement(sql);            if (parameters != null) {                for (int i = 0; i < parameters.length; i++) {                    pstmt.setString(i + 1, parameters[i]);                }            }            System.out.println(pstmt);            rs = pstmt.executeQuery();        } catch (Exception e) {            e.printStackTrace();            throw new RuntimeException(e.getMessage());        } finally {            // 如果这里关闭了资源,就没法使用ResultSet了,也就没法return了            // close(rs, pstmt, conn);        }        return rs;    }    //修改后的统一的select (ResultSet-->ArrayList)    public static ArrayList executeQuery1(String sql,String[] parameters){        ArrayList list = new ArrayList();        try {            conn = getConnection();            pstmt = conn.prepareStatement(sql);            if(parameters!=null){                for (int i = 0; i < parameters.length; i++) {                    pstmt.setString(i+1, parameters[i]);                }            }            System.out.println(pstmt);            rs = pstmt.executeQuery();            ResultSetMetaData rsmd = rs.getMetaData();            int column = rsmd.getColumnCount();//这里可以得到你查询语句返回的总的列数            while (rs.next()) {                Object[] ob = new Object[column];//对象数组,表示一行数据                for (int i = 0; i < column; i++) {                    ob[i] = rs.getObject(i+1);                }                list.add(ob);            }            return list;        } catch (Exception e) {            e.printStackTrace();            throw new RuntimeException(e.getMessage());        } finally{            //关闭资源            close(rs, pstmt, conn);        }    }}

8.Hibernate工具类

package com.huihui.util;import java.util.List;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;final public class HibernateUtil {    private static SessionFactory sessionFactory = null;    // 使用线程局部模式    private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();    private HibernateUtil() {    }    static {        sessionFactory = new Configuration().configure().buildSessionFactory();    }    // 获取一个全新的Session    public static Session openSession() {        return sessionFactory.openSession();    }    // 获取和线程关联的Session    public static Session getCurrentSession() {        Session session = threadLocal.get();        // 判断是否得到了        if (session == null) {            session = sessionFactory.openSession();            // 把session对象设置到threadLocal中去,相当于该Session已经和线程绑定            threadLocal.set(session);        }        return session;    }    //统一的修改和删除    public static void executeUpdate(String hql,String[] parameters){        Session session = null;        Transaction transaction = null;        try {            session = openSession();            transaction = session.beginTransaction();            Query query = session.createQuery(hql);            if(parameters!=null&&parameters.length>0){                for (int i = 0; i < parameters.length; i++) {                    query.setString(i, parameters[i]);                }            }            query.executeUpdate();            transaction.commit();        } catch (Exception e) {            if(transaction!=null){                transaction.rollback();            }            e.printStackTrace();            throw new RuntimeException(e.getMessage());        } finally{            if(session!=null&&session.isOpen()){                session.close();            }        }    }    //统一的添加方法    public static void save(Object obj){        Session session = null;        Transaction transaction = null;        try {            session = openSession();            transaction = session.beginTransaction();            session.save(obj);            transaction.commit();        } catch (Exception e) {            if(transaction!=null){                transaction.rollback();            }            e.printStackTrace();            throw new RuntimeException(e.getMessage());        } finally{            if(session!=null&&session.isOpen()){                session.close();            }        }    }    //提供返回只有一个结果的查询(一个结果)    public static Object executeQueryForOne(String hql,String[] parameters){        Object o = null;        Session session  = null;        try {            session = openSession();            Query query = session.createQuery(hql);            if(parameters!=null&&parameters.length>0){                for (int i = 0; i < parameters.length; i++) {                    query.setString(i, parameters[i]);                }            }            o = query.uniqueResult();        } catch (Exception e) {            e.printStackTrace();            throw new RuntimeException(e.getMessage());        } finally{            if(session!=null&&session.isOpen()){                session.close();            }        }        return o;    }    // 提供一个统一的查询方法(带分页)    public static List executeQueryByPage(String hql, String[] parameters,            int pageSize, int pageNow) {        List list = null;        Session session = null;        try {            session = openSession();            Query query = session.createQuery(hql);            if(parameters!=null&&parameters.length>0){                for (int i = 0; i < parameters.length; i++) {                    query.setString(i, parameters[i]);                }            }            query.setFirstResult((pageNow-1)*pageSize).setMaxResults(pageSize);            list = query.list();        } catch (Exception e) {            e.printStackTrace();            throw new RuntimeException(e.getMessage());        } finally{            if(session!=null&&session.isOpen()){                session.close();            }        }        return list;    }    // 提供统一的查询方法.hql形式:from 类 where 条件=?...(多个结果)    public static List executeQuery(String hql, String[] parameters) {        Session session = null;        Transaction transaction = null;        List list = null;        try {            session = getCurrentSession();            transaction = session.beginTransaction();            Query query = session.createQuery(hql);            if (parameters != null && parameters.length > 0) {                for (int i = 0; i < parameters.length; i++) {                    query.setString(i, parameters[i]);                }            }            list = query.list();            transaction.commit();        } catch (Exception e) {            if (transaction != null) {                transaction.rollback();            }            e.printStackTrace();            throw new RuntimeException(e.getMessage());        } finally {            if (session != null && session.isOpen()) {                session.close();            }            session = null;        }        return list;    }}

9.图片验证码生成器

基础的验证码包括了数字、字母、甚至可能有汉字。下面我给出一个简单的工具类

package com.huihui.test5;import java.awt.Color;import java.awt.Font;import java.awt.Graphics2D;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.util.Date;import java.util.Random;import javax.imageio.ImageIO;/** * 验证码生成器 */public class ValidateCode {    // 图片的宽度。    private int width = 160;    // 图片的高度。    private int height = 40;    // 验证码字符个数    private int codeCount = 5;    // 验证码干扰线数    private int lineCount = 150;    // 验证码    private static String code = null;    // 验证码图片Buffer    private BufferedImage buffImg = null;    private char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R',            'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' };    public ValidateCode() {        this.createCode();    }    /**     *      * @param width     *            图片宽     * @param height     *            图片高     */    public ValidateCode(int width, int height) {        this.width = width;        this.height = height;        this.createCode();    }    /**     *      * @param width     *            图片宽     * @param height     *            图片高     * @param codeCount     *            字符个数     * @param lineCount     *            干扰线条数     */    public ValidateCode(int width, int height, int codeCount, int lineCount) {        this.width = width;        this.height = height;        this.codeCount = codeCount;        this.lineCount = lineCount;        this.createCode();    }    public void createCode() {        int x = 0, fontHeight = 0, codeY = 0;        int red = 0, green = 0, blue = 0;        x = width / (codeCount + 1);// 每个字符的宽度        fontHeight = height - 2;// 字体的高度        codeY = height - 3;        // 图像buffer        buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);        Graphics2D g = buffImg.createGraphics();        // 生成随机数        Random random = new Random();        // 将图像填充为白色        g.setColor(Color.WHITE);        g.fillRect(0, 0, width, height);        // 创建字体        ImgFontByte imgFont = new ImgFontByte();        Font font = imgFont.getFont(fontHeight);        g.setFont(font);        for (int i = 0; i < lineCount; i++) {            int xs = random.nextInt(width);            int ys = random.nextInt(height);            int xe = xs + random.nextInt(width / 8);            int ye = ys + random.nextInt(height / 8);            red = random.nextInt(255);            green = random.nextInt(255);            blue = random.nextInt(255);            g.setColor(new Color(red, green, blue));            g.drawLine(xs, ys, xe, ye);        }        // randomCode记录随机产生的验证码        StringBuffer randomCode = new StringBuffer();        // 随机产生codeCount个字符的验证码。        for (int i = 0; i < codeCount; i++) {            String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);            // 产生随机的颜色值,让输出的每个字符的颜色值都将不同。            red = random.nextInt(255);            green = random.nextInt(255);            blue = random.nextInt(255);            g.setColor(new Color(red, green, blue));            g.drawString(strRand, (i + 1) * x, codeY);            // 将产生的四个随机数组合在一起。            randomCode.append(strRand);        }        // 将四位数字的验证码保存到Session中。        code = randomCode.toString();    }    public void write(String path,String fileName) throws IOException {        File folder = new File(path);        if(!folder.exists()){            folder.mkdirs();        }        OutputStream sos = new FileOutputStream(path+fileName);        this.write(sos);    }    public void write(OutputStream sos) throws IOException {        ImageIO.write(buffImg, "png", sos);        sos.close();    }    public BufferedImage getBuffImg() {        return buffImg;    }    public String getCode() {        return code;    }    public static void main(String[] args) {          ValidateCode vCode = new ValidateCode(120,40,5,50);          try {              String path="C:\\Users\\Administrator\\Desktop\\";              System.out.println(vCode.getCode()+" >"+path);              vCode.write(path,new Date().getTime()+".png");          } catch (IOException e) {              e.printStackTrace();        }       }}

下面这个类主要是用作字体的设置:

package com.huihui.test5;import java.awt.Font;import java.io.ByteArrayInputStream;public class ImgFontByte {     public Font getFont(int fontHeight){              try {                  Font baseFont = Font.createFont(Font.ITALIC, new ByteArrayInputStream(hex2byte(getFontByteStr())));                 return baseFont.deriveFont(Font.PLAIN, fontHeight);              } catch (Exception e) {                  return new Font("Consola",Font.PLAIN, fontHeight);              }          }          private  byte[] hex2byte(String str) {               if (str == null)                  return null;              str = str.trim();              int len = str.length();              if (len == 0 || len % 2 == 1)                  return null;              byte[] b = new byte[len / 2];              try {                  for (int i = 0; i < str.length(); i += 2) {                      b[i/2] = (byte) Integer.decode("0x" + str.substring(i, i + 2)).intValue();                  }                  return b;              } catch (Exception e) {                  return null;              }          }      /**       * ttf字体文件的十六进制字符串       * @return       */       private String getFontByteStr(){          return null;       }  }
0 0