标签 java 下的文章

也许是由于版本的原因,把SpringBoot2的改为了SpringBoot1.5,发现在swagger这个接口文档突然不能用了。出现了下面的错误

Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. The base url is the root of where all the swagger resources are served. For e.g. if the api is available at http://example.org/api/v2/api-docs then the base url is http://example.org/api/. Please enter the location manually:

解决办法:
在ApiApplication里面添加@EnableSwagger2

SpringBoot开启日志
在SpringBoot的配置文件application.properties文件里加入以下内容

#com.mycompany.mavenspringboot.controller 日志 WARN级别输出
logging.level.com.univalsoft.api.controller=WARN
#com.mycompany.mavenspringboot.mapper sql日志 DEBUG级别输出
logging.level.com.mycompany.mavenspringboot.mapper=DEBUG

logging.file=logs/spring-boot-logging.log
logging.pattern.console=%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger- %msg%n
logging.pattern.file=%d{yyyy/MM/dd-HH:mm} [%thread] %-5level %logger- %msg%n

java本身转码解码

  • 编码

    public static String getBASE64(String str) {
         if (str == null) return null;
         return (new sun.misc.BASE64Encoder()).encode( str.getBytes() );
    }
  • 解码

    public static String getFromBASE64(String str) {
         if (str == null) return null;
         BASE64Decoder decoder = new BASE64Decoder();
         try {
             byte[] b = decoder.decodeBuffer(s);
             return new String(b);
         } catch (Exception e) {
             return null;
         }
     }

    利用apache的包

  • 编码

       public static String encode(byte[] binaryData) {
         try {
             return new String(Base64.encodeBase64(binaryData), "UTF-8");
         } catch (UnsupportedEncodingException e) {
             return null;
         }
     }
  • 解码

    public static byte[] decode(String base64String) {
          try {
              return Base64.decodeBase64(base64String.getBytes("UTF-8"));
          } catch (UnsupportedEncodingException e) {
              return null;
          }
      } 

DBUtils封装了对JDBC的操作,简化了JDBC的操作,是java编程中数据库操作的实用工具。

三个核心:

  • QueryRunner中提供了对sql语句操作的API。

    • QueryRunner(DataSource ds),提供数据源(连接池),DBUtils底层自动维护连接connection。
    • update(String sql,Object... params),执行更新数据。
    • query(String sql,ResultSetHandlerrsh,Object...params),执行查询。
  • ResultSetHandler接口,用于定义select操作后,封装结果集。(在下面的案例中有提现)。
  • DBUtils类,这是一个工具类,定义了关闭资源与事务处理的方法。

    • closeQuietly(Connection conn)关闭连接,如果有异常,使用try进行处理。
    • commitAndCloseQuietly(Connection conn)提交并关闭连接。
    • rollbackAndCloseQuietly(Connection conn)回滚并关闭连接。

基本步骤

1.创建核心类QueryRunner
2.编写SQL语句
3.为占位符设置值
4.执行操作

案例

注意:案例使用到了C3P0连接池,不会的小伙伴请参考小编以前的文章哦。

  • 添加操作

    public void testAddUser() {
          try {
              //1.创建核心类QueryRunner
              QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
              //2.编写SQL语句
              String sql = "insert into users values(null,?,?)";
              //3.为占位符设置值
              Object[] params = {"12","34"};
              //4.执行添加操作
              int rows = qr.update(sql,params);
              if (rows>0) {
                  System.out.println("添加成功");
              }else {
                  System.out.println("添加失败");
              }
          } catch (SQLException e) {
              e.printStackTrace();
          }
      }
  • 修改操作

    public void testUpdateUserById() {
          try {
              //1.创建核心类QueryRunner
              QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
              //2.编写SQL语句
              String sql = "update users set upwd = ? where uid = ?";
              //3.为占位符设置值
              Object[] params = {"1212",1};
              //4.执行修改操作
              int rows = qr.update(sql,params);
              if(rows>0) {
                  System.out.println("修改成功");
              }else {
                  System.out.println("修改失败");
              }
          } catch (SQLException e) {
              e.printStackTrace();
          }
          
      }
  • 删除操作

    public void testDeleteUserById() {
          
          try {
              //1.创建核心类QueryRunner
              QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
              //2.编写SQL语句
              String sql = "delete from Users where uid = ?";
              //3.为占位符设置值
              Object[] params = {2};
              //4,执行删除操作
              int rows = qr.update(sql,params);
              if (rows>0) {
                  System.out.println("删除成功");
              }else {
                  System.out.println("删除失败");
              }
          } catch (SQLException e) {
              e.printStackTrace();
          }
          
      }
  • 查询操作(种类较多)

    public class TestDBUtils2{
      
      /**
       * 查询所有用户方法
       */
      @Test
      public void testQueryAll() {
          try {
              //1,获取核心类queryRunner
              QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
              //2.编写sql语句
              String sql = "select * from users";
              //3.执行结果查询
              List<User> users = qr.query(sql, new BeanListHandler<User>(User.class));
              //4.对结果集集合进行遍历
              for(User user : users) {
                  System.out.println(user.getUname()+"---"+user.getUpwd());
              }
          } catch (SQLException e) {
              e.printStackTrace();
          }
          
      }
      
      /**
       * 根据id查询用户
       */
      @Test
      public void testQueryUserById() {
          
          try {
              //1.获取核心类queryRunner
              QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
              //2.编写sql语句
              String sql = "select * from users where uid = ?";
              //3.为占位符设置值
              Object[] params = {1};
              //4.执行查询操作
              User user = qr.query(sql, new BeanHandler<User>(User.class),params);
              //5.输出结果
              System.out.println(user.getUname()+"---"+user.getUpwd());
          } catch (SQLException e) {
              e.printStackTrace();
          }
      }
      
      /**
       * 查询用户的数量
       */
      @Test
      public void testQueryCount() {
          
          try {
              //1.获取核心类queryRunner
              QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
              //2.编写sql语句
              String sql = "select count(*) from users";
              //3.执行查询语句
              Long count = (Long)qr.query(sql, new ScalarHandler());
              //4.输出结果
              System.out.println(count);
          } catch (SQLException e) {
              e.printStackTrace();
          }
      }
      /**
       * 查询所有用户
       */
      @Test
      public void testQueryAll1() {
          
          try {
              //1.获取核心类
              QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
              //2.编写sql语句
              String sql = "select * from users";
              //3.执行查询操作
              List<Map<String, Object>> list = qr.query(sql, new MapListHandler());
              //4.对结果集进行遍历
              for (Map<String, Object> map : list) {
                  System.out.println(map);
              }
          } catch (SQLException e) {
              e.printStackTrace();
          }
          
      }
      
      /**
       * 查询所有用户
       */
      @Test
      public void testQueryAll2() {
          
          try {
              //1.获取核心类queryRunner
              QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
              //2,编写sql
              String sql = "select * from users";
              //3.执行查询操作
              List<Object> List = qr.query(sql,new ColumnListHandler("uname"));
              //4.对结果集进行遍历
              for (Object object : List) {
                  System.out.println(object);
              }
          } catch (SQLException e) {
              e.printStackTrace();
          }
          
      }
     }

DBCP是tomcat内置的连接池。
使用方法:

  • 导入jar包
    1.png
  • 书写配置文件

    • 配置文件名称:*.properties(文件名任意,但是扩展名固定)。
    • 位置任意,一般放在src目录下。
    • 不能写中文。
    • 内容(其他配置也写在这里面):

       driver=com.mysql.jdbc.Driver
       url=jdbc:mysql://127.0.0.1:3306/ning
       username=root
       password=root
  • 工具类:

    package com.sunxiaoning.jdbc.utils;
    
    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.SQLException;
    import java.util.Properties;
    
    import javax.sql.DataSource;
    
    import org.apache.commons.dbcp.BasicDataSourceFactory;
    
    /**
     * DBCP工具类
     * @author sunxiaoning
     *
     */
    public class DBCPUtils {
      private static DataSource dataSource;
      static {
          
          try {
              //1.加载找properties文件输入流
              InputStream is = DBCPUtils.class.getClassLoader().getResourceAsStream("db.properties");
              //2.加载输入流
              Properties props = new Properties();
              props.load(is);
              //3.创建数据源
              dataSource = BasicDataSourceFactory.createDataSource(props);
              
          } catch (Exception e) {
              throw new RuntimeException();
          }
       }
      
      /**
       * 获取数据源(连接池)
       * @return
       */
      public static DataSource getDataSource() {
          return dataSource;
      }
      
      /**
       * 获得连接
       * @return
       */
      public static Connection getConnection() {
          try {
              return dataSource.getConnection();
          } catch (SQLException e) {
              throw new RuntimeException();
          }
      }
    }
    
  • 测试类

    package com.sunxiaoning.jdbc.test;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    
    import org.junit.jupiter.api.Test;
    
    import com.sunxiaoning.jdbc.utils.DBCPUtils;
    
    public class TestDBCP {
      
      @Test
      public void testUpdateByid() {
          Connection conn = null;
          PreparedStatement pstmt = null;
          try {
              conn = DBCPUtils.getConnection();
              String sql = "update users set upwd =? where uid =?";
              pstmt = conn.prepareStatement(sql);
              pstmt.setString(1, "222");
              pstmt.setInt(2, 1);
              int rows = pstmt.executeUpdate();
              if(rows>0) {
                  System.out.println("更新成功");
              }else {
                  System.out.println("更新失败");
              }
          } catch (Exception e) {
              throw new RuntimeException();
          }finally {
              if (conn!=null) {
                  try {
                      conn.close();
                  } catch (SQLException e) {
                      e.printStackTrace();
                  }
              }
              
              if(pstmt!=null) {
                  try {
                      conn.close();
                  } catch (SQLException e) {
                      e.printStackTrace();
                  }
              }
              
          }
          
      }
    }
    

C3P0是一款开源免费的连接池,连接池的主要作用就是提高性能。
使用方法:

  1. 导入jar包:c3p0的jar包和mysql的jar包(小编使用的是mysql数据库),这两个jar包可以自行百度下载。也可以给小编留言哦。
  2. 编写配置文件c3p0-config.xml

    • 配置文件的名称必须为:c3p0-config.xml;
    • 一般情况放在src目录里面。
    • 文件的配置(以下是主要配置,其他选项可以参考手册)

      <?xml version="1.0" encoding="UTF-8"?>
      <c3p0-config>
       <default-config>
      <!-- 连接数据库的参数 -->
      <property name="driverClass">com.mysql.jdbc.Driver</property>
      <property name="jdbcUrl">jdbc:mysql:///ning</property>
      <property name="user">root</property>
      <property name="password">root</property>
      <!-- 初始化连接数 -->
      <property name="initialPoolSize">5</property>
      <!-- 最大连接数 -->
      <property name="maxPoolSize">20</property>
       </default-config>
       <named-config name="ning">
      <property name="driverClass">com.mysql.jdbc.Driver</property>
      <property name="jdbcUrl">jdbc:mysql:///ning</property>
      <property name="user">root</property>
      <property name="password">root</property>
       </named-config>
      </c3p0-config>
  3. 工具类

    package com.sunxiaoning.jdbc.utils;
    
    import java.sql.Connection;
    import java.sql.SQLException;
    
    import com.mchange.v2.c3p0.ComboPooledDataSource;
    
    public class C3P0Utils {
     private static ComboPooledDataSource dataSource = new ComboPooledDataSource("itheima");
     
     /**
      * 获得数据源(连接池)
      * @return
      */
     public static ComboPooledDataSource getDataSource() {
         return dataSource;
     }
     
     /**
      * 获得连接
      * @return
      */
     public static Connection getConnection() {
         try {
             return dataSource.getConnection();
         } catch (SQLException e) {
             throw new RuntimeException();
         }
     }
     
     /**
      * 归还连接
      * @param conn
      */
     public static void closeConn(Connection conn){
         try {
             if(conn!=null && conn.isClosed()){
                 conn.close();
             }
         } catch (SQLException e) {
             e.printStackTrace();
         }
     }
    }
    

    附录:测试类

    package com.sunxiaoning.jdbc.test;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    
    import org.junit.jupiter.api.Test;
    
    import com.sunxiaoning.jdbc.utils.C3P0Utils;
    /**
     * 测试C3P0
     * @author sunxiaoning
     *
     */
    package com.sunxiaoning.jdbc.test;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    
    import org.junit.jupiter.api.Test;
    
    import com.sunxiaoning.jdbc.utils.C3P0Utils;
    /**
     * 测试C3P0
     * @author sunxiaoning
     *
     */
    public class TestC3P0 {
    
     @Test
     public void testAddUser() {
         Connection conn = null;
         PreparedStatement pstmt = null;
         
         try {
             conn = C3P0Utils.getConnection();
             String sql = "insert into users values(null,?,?)";
             pstmt = conn.prepareStatement(sql);
             pstmt.setString(1, "小宁");
             pstmt.setString(2, "qwe");
             int row = pstmt.executeUpdate();
             if(row>0) {
                 System.out.println("添加成功");
             }else {
                 System.out.println("添加失败");
             }
         } catch (SQLException e) {
             throw new RuntimeException();
         }finally {
             C3P0Utils.closeConn(conn);
             if (pstmt!=null) {
                 try {
                     pstmt.close();
                 } catch (SQLException e) {
                     e.printStackTrace();
                 }
             }
         }
         
     }
    }
    

时间转换为时间戳(10位)

    public static long dateToTimestamp(String time) {
 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 try {
     Date date = simpleDateFormat.parse(time);
     long ts = date.getTime()/1000;
     return ts;
 } catch (ParseException e) {
     return 0;
 }
    }

时间戳转换诶时间

    public static String timestampToDate(long time) {
 if (time < 10000000000L) {
     time = time * 1000;
 }
 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 String sd = sdf.format(new Date(Long.parseLong(String.valueOf(time))));
 return sd;
    }

获取当前时间戳(13位)

    public static long nowData() {
// 方法 一
// long data = System.currentTimeMillis();
// 方法 二
long data = Calendar.getInstance().getTimeInMillis();
// 方法三
// long data = new Date().getTime();
return data;

    }

获取当前时间(yyyy-MM-dd hh:mm:ss)

    public static String nowTime() {
 Date currentTime = new Date();// 获取当前时间
 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");// 格式化时间
 String dateString = formatter.format(currentTime);// 转换为字符串
 return dateString;
    }

比较时间大小

     public static int compare_date(String DATE1, String DATE2) {
   DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
   try {
       Date dt1 = df.parse(DATE1);
       Date dt2 = df.parse(DATE2);
       if (dt1.getTime() > dt2.getTime()) {
           return 1;
       } else if (dt1.getTime() < dt2.getTime()) {
           return -1;
       } else {
           return 0;
       }
   } catch (Exception exception) {
       exception.printStackTrace();
   }
   return 0;
        }

字符串转换为时间

    public static Date strToData(String data,String format) {
 Date date = null;
 try {
     date = new SimpleDateFormat(format).parse(data);
 } catch (ParseException e) {
     e.printStackTrace();
 }
 return date;
    }

时间格式化

    public static String parseTimestamp(String format) {
Date now = new Date();
SimpleDateFormat f = new SimpleDateFormat(format);
return f.format(now);
    }

附录1:为什么会生成13位的时间戳,13位的时间戳和10时间戳分别是怎么来的
原来java的date默认精度是毫秒,也就是说生成的时间戳就是13位的,而像c++或者php生成的时间戳默认就是10位的,因为其精度是秒。
附录2:13位时间戳如何转换成10位时间戳
本来以为java中有设置可以修改其时间精度,后来在百度上没有找到,就只能采用其它方法来转化,这里提供两种方式来转换。
第一种:通过substring方法,将13位的时间戳最后三位数字截取。
第二种:将13位时间戳除以1000取整。
小编使用的是第二种,在上面的代码中也有提现。

int转换为String(int i=100)

第一种方法:s=i+""; //会产生两个String对象
第二种方法:s=String.valueOf(i); //直接使用String类的静态方法,只产生一个对象。

String转换为int(Sting s="100")

第一种方法:i=Integer.parseInt(s); //直接使用静态方法,不会产生多余的对象,但会抛出异常
第二种方法:i=Integer.valueOf(s).intValue();//Integer.valueOf(s) 相当于 new Integer(Integer.parseInt(s)),也会抛异常,但会多产生一个对象,

字符串转换为float

float f = Float.parseFloat(str);

字符串转double

String str = "123.002";Double d ;d = Double.parseDouble(str);

String转换为byte[]

String string = "hello world";
byte[] bytes = string.getBytes();

byte[]转换为String

String s = new String(bytes);

通过Base64将String与byte进行转换

import java.util.Base64;
public class test 
{
    public static void main(String[] args) 
    {
        byte[] bytes = "hello world".getBytes();
        String encoded = Base64.getEncoder().encodeToString(bytes);
        byte[] decoded = Base64.getDecoder().decode(encoded);
        for(byte a : decoded)
            System.out.println(a);
        System.out.println( new String(decoded) );
    }
}

String转换为数组

String str = "a,b,bb,dd";

  1. String[] strArr = str.split(",");
  2. char[] charArr = str.toCharArray();
  3. byte[] byteArr = str.getBytes();

字符数组转换为字符串:

char[] c1 = {'a','b','c'};String str = new String(c1);

需求:首先获取一个base64格式的图片,然后保存在指定文件夹内,并且新建时间文件夹进行区分,如果时间文件夹存在就直接存储,时间文件夹不存在就新建文件夹。

 /**
     * 保存图片
     *
     * @param base64image 图片base64字符串
     * @param name 图片保存之后的名称
     * @return 文件名
     */
    public static String saveBase64Image(String base64image,String name) {

        Date date = new Date();
        String dataForm = new SimpleDateFormat("yyyy-MM-dd").format(date);
        String filePath = PropertiesTools.applicationProperty("app.image.path") + dataForm + '/';
        File file = new File(filePath);
        if (!file.exists()) {//如果文件夹不存在
            file.mkdir();//创建文件夹
        }

        String fileType = FileTools.base64imageType(base64image);// "a.png";
        String fileName = FileTools.randomFileName(null);
        String fileContent = FileTools.base64imageContent(base64image);
        String imageFullName = name + "." + fileType;

        FileTools.saveBase64Images(fileContent, filePath + imageFullName);
        return dataForm+'/'+imageFullName;
    }

    /**
     * 保存图片
     *
     * @param base64str 图片base64字符串
     * @param filePath  完整的文件路径(包含文件名)
     * @return 文件地址
     */
    public static String saveBase64Images(String base64str, String filePath) {

        // 参数校验
        if (base64str == null || filePath == null)
            return null;

        // 检查目录是否存在,同时生成目录
        String fileDirectory = FileTools.directoryFromPath(filePath);
        if (!FileTools.generateDirectory(fileDirectory)) {
            return null;
        }

        // 存储文件
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(base64str);
            for (int i = 0; i < b.length; ++i) {
                //调整异常数据
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }

            //生成jpeg图片
            OutputStream out = new FileOutputStream(filePath);
            out.write(b);
            out.flush();
            out.close();

            return filePath;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

在项目的实际开发过程中会经常用到有关时间的处理,比如获取当前的时间,获取当前的时间戳等。而且我们为了更加的规范往往还需要对时间的格式进行统一的处理。并且还有灵活的对事件以及时间戳进行转换。在实际的项目开发过程中,往往把这些内容抽取处理,作为单独的工具类,小编这里就自己整理了一个时间处理的工具类,若果有不完善的地方,大家一起讨论。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTools {

    /**
     * 当前时间-时间戳
     *
     * @return 根路径
     */
    public static int timestamp() {
        long time = System.currentTimeMillis();
        return (int) (time / 1000);
    }

    /**
     * 获取当前时间-时间(yyyy-MM-dd HH:mm:ss)
     *
     * @return
     */
    public static String timesNow() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }

    /**
     * 格式化时间,默认“yyyy-MM-dd hh:mm:ss”
     *
     * @param timestamp
     * @return
     */
    public static String parseTimestamp(long timestamp) {
        return parseTimestamp(timestamp, "yyyy-MM-dd hh:mm:ss");
    }

    /**
     * 当前格式化时间
     *
     * @return
     */
    public static String formatNow(String aFmt) {
        Date date = new Date();
        String fmt = aFmt;
        if (fmt == null) {
            fmt = "yyyy-MM-dd hh:mm:ss";
        }
        SimpleDateFormat dateFmt = new SimpleDateFormat(fmt);
        String dateStr = dateFmt.format(date);
        return dateStr;
    }

    /**
     * 格式化时间
     *
     * @param timestamp
     * @param fmt       时间格式化字符串
     * @return
     */
    public static String parseTimestamp(long timestamp, String fmt) {
        Date date = new Date(timestamp * 1000);
        SimpleDateFormat dateFmt = new SimpleDateFormat(fmt);
        String dateStr = dateFmt.format(date);
        return dateStr;
    }

    /**
     * 时间转换为时间戳
     *
     * @param time
     * @return
     */
    public static long dateToTimestamp(String time) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = simpleDateFormat.parse(time);
            long ts = date.getTime() / 1000;
            return ts;
        } catch (ParseException e) {
            return 0;
        }
    }

    /**
     * 时间戳(10位)转换为时间
     * @param time
     * @return
     */
    public static String timestampToDate(Long time) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sd = sdf.format(new Date(Long.parseLong(String.valueOf(time*1000))));
        return sd;
    }

}