学习笔记之代码记录

博主为方便二次查阅,创建了一篇文章记录Java SE和Java Web的学习代码,包括面向对象、常用类、集合、异常、线程、JDBC、JQuery、AJAX与JSON以及Redis的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我发现我写过的代码第二次再写的时候就不记得了,还得去看一遍才会写,所以专门用一篇文章记录各个阶段的代码供自己闲暇时候翻翻看。

  1. Java SE
    1. 面向对象程序设计的相关使用
    2. 常用类的相关使用
    3. 集合的相关使用
    4. 异常的相关使用
    5. 线程的相关使用
    6. JDBC的相关使用
  2. Java Web
    1. JQuery
    2. AJAXAndJSON
    3. Redis

面向对象程序设计的相关使用

public class Fu {
    public String name;
    private int age;

    public Fu() {
        name="lisi";
        age=24;
    }

    public String getName() {
        return name;
    }
}
public class Zi extends Fu{
    public String name;
    private int age;

    public Zi() {
        name="zhangsan";
        age=23;
    }

    @Override
    public String getName() {
        return name;
    }
}
public static void main(String[] args) {
    Fu fu=new Zi();
    System.out.println(fu.getName());//子类的name
    System.out.println(fu.name);//父类的name
}

常用类的相关使用

new Random().nextDouble();//没有参数。
new Random().nextInt(1);//只有这个next方法有重载可赋值参数,左闭右开区间,nextBytes()方法则必须有参数。
System.out.println(9+5+"8");//148
System.out.println("9"+5+8);//958
System.out.println(Arrays.toString(new int[]{1}));//Arrays.toString()没有无参重写,则会调用Object类的toString()。
//Arrays.toString()空参会提示Non-static method 'toString' cannot be referenced from a static context。

集合的相关使用

int[] ints = {1, 2, 3};
ArrayList<Integer> arrayList = new ArrayList<>();//从JDK7开始右侧尖括号可省略泛型
arrayList.add(1);arrayList.add(2);arrayList.add(3);
HashSet hashSet = new HashSet();
hashSet.addAll(arrayList);
HashMap hashMap = new HashMap();
hashMap.put("1", "1");hashMap.put("2", "2");hashMap.put("3", "3");
List list = new LinkedList();
list.addAll(arrayList);
System.out.println(ints);//[I@312b1dae
System.out.println(arrayList);//[1, 2, 3]
System.out.println(hashSet);//[1, 2, 3]
System.out.println(list);//[1, 2, 3]
System.out.println(hashMap);//{1=1, 2=2, 3=3}
public static void main(String[] args) {
   Map map=new HashMap();
   map.put("1","1");
   map.put("2","2");
   map.put(null,"2");
   map.put(null,"1");
    Set keys = map.keySet();
    keys.forEach(System.out::println);//null 1 2
    keys.forEach(s-> System.out.println(map.get(s)));//1 1 2
    System.out.println(map);//null=1,1=1,2=2}
    System.out.println(map.get("a"));//null Map找不到对应的key值不会报错,会返回null值。
}

异常的相关使用

public static void main(String[] args) {
    try {
        int i =1/0;
    }catch (Exception e){
        e.printStackTrace();//  java.lang.ArithmeticException: / by zero
        //  at NativeJDBC.NativeJDBCTest.main(NativeJDBCTest.java:12)   JVM打印异常对象,默认此方法,打印的异常信息是最全面的。
        System.out.println(e);//  java.lang.ArithmeticException: / by zero  打印异常类型和简短描述
        System.out.println(e.getCause());//  null   该方法返回一个Throwable,即引起该异常的真正的异常。
        System.out.println(e.getMessage());//  / by zero   该方法返回Throwable的简短描述。
    }   
}

线程的相关使用

public static void main(String[] args) {
    //JDK1.5之后提供线程池。
    //java.util.concurrent.Executors 线程池的工厂类。
    //static ExecutorService newFixedThreadPool(int nThreads);
    //static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory);
    //java.util.concurrent.ExecutorService 线程池接口submit(Runnable task);void shutdown();
    ExecutorService executorService = Executors.newFixedThreadPool(9);
    executorService.submit(()-> System.out.println("该线程执行的具体内容。"));
    executorService.shutdown();
}

JDBC的相关使用

public class JDBCUtils {
    private static DataSource druidDataSource;
    static {
        Properties properties=new Properties();
        InputStream inputStream = JDBCUtils.class.getResourceAsStream("/druid.properties");
        // JDBCUtils.class.getClassLoader().getResourceAsStream("/druid.properties");这样写也可以,实际上类对象的getResourceAsStream
        //方法里面创建了类加载器然后还是调用类加载器的getResourceAsSteam方法。
        try {
            properties.load(inputStream);
            druidDataSource=DruidDataSourceFactory.createDataSource(properties);
            //这里的参数可以传入Properties和Map类型。
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static DataSource getDataSource(){return druidDataSource;}
    public static Connection getConnection() throws SQLException {return druidDataSource.getConnection();}
}

```java
public static void main(String[] args) {
    String driver="com.mysql.cj.jdbc.Driver";
    String dburl="jdbc:mysql:///mydb?serverTimezone=UTC&useSSL=false";
    String username="root";
    String password="root";
    try{
        Class.forName(driver);//加载驱动程序,mysql8此句可以省略,自动注册驱动。
        Connection connection = DriverManager.getConnection(dburl, username, password);
        //创建连接对象可以通过DriverManager和DataSource接口,后者一般用于数据库连接池。
        connection.prepareStatement("SELECT * FROM MYTABLE");
        connection.createStatement();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

JQuery

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>  //在线引入JQuery框架。
<script>
	$(function(){
		for(li of $(Objects)){
		li.innerHTML;  //这里的li是js元素,且不能使用this,JQuery 3.0之后提供的遍历方式。
		};
		for([var] x in jsonArrayObject){
		jsonArrayObject[x].data;  //这个是我没学之前写的,也能用。这里的x是从0开始的索引,刚开始我还以为是js元素,并没有人教我这样写,但是能用的话也记录一下。
		};
		var jsonObject=eval("("+jsonString+")");  //这里括号一定要加,不然有可能当做函数执行,不会转成json对象。
		
	});
	
</script>

AJAXAndJSON

<html>
  <head>
    <title>$Title$</title>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script>
      var xmlHttp;
      function createXMLHttpRequest() {
        if (window.XMLHttpRequest){
          xmlHttp=new XMLHttpRequest();
        }else {
          xmlHttp=new ActiveXObject("Microsoft:XMLHTTP");
        }
      }

      function changeJSPData(xmlHttp) {
        var selectElement= document.getElementById("selectProvince");
        var jsonString = xmlHttp.responseText;
        var jsonObject = eval("("+jsonString+")");
        for (x in jsonObject) {
          var htmlOptionElement = document.createElement("option");
          var textNode = document.createTextNode(jsonObject[x].name);
          htmlOptionElement.setAttribute("id",jsonObject[x].id);
          htmlOptionElement.appendChild(textNode);
          selectElement.appendChild(htmlOptionElement);
        }
      }

      function handleReadyStateChange() {
        if (xmlHttp.readyState==4){
          if (xmlHttp.status==200){
            changeJSPData(xmlHttp);
          }
        }
      }

      function queryProvince() {
        createXMLHttpRequest();
        xmlHttp.onreadystatechange=handleReadyStateChange;
        xmlHttp.open("GET","/provinceServlet",true);
        xmlHttp.send(null);
      }

      $(function () {
        queryProvince();
      })
    </script>
  </head>
  <body>
  <select id="selectProvince">
    <option>---请选择省份---</option>
  </select>
  </body>
</html>

Redis

//需要用到jedis.jar包。
public static void main(String[] args) {
    Jedis jedis = new Jedis("localhost",6379);//如果是默认值可以省略书写。
    //操作字符串string。
    jedis.set("name","zhangsan");
    jedis.get("name");
    jedis.setex("activecode",20,"hehe");//20秒后自动删除该键值对。

    //操作哈希hash。
    jedis.hset("person","name","zhangsan");
    jedis.hset("person","age","23");
    jedis.hget("person","name");
    jedis.hgetAll("person");//{name=zhangsan, age=23}

    //操作列表linkedlist。
    jedis.lpush("mylist","a","b","c");
    jedis.rpush("mylist","a","b","c");
    jedis.lrange("mylist",0,-1);//[c, b, a, a, b, c]
    jedis.lpop("mylist");//c
    jedis.rpop("mylist");//c

    //操作集合set。
    jedis.sadd("myset","java","php","c++");
    jedis.smembers("myset");//[c++, php, java]

    //操作有序集合sortedset。
    jedis.zadd("mysortedset",3,"yase");
    jedis.zadd("mysortedset",30,"houyi");
    jedis.zadd("mysortedset",55,"sunwukong");
    jedis.zrange("mysortedset", 0, -1);//[yase, houyi, sunwukong]
    jedis.close();
}
@Test
public void test1(){
    //需要导入commons-pool.jar包。
    JedisPoolConfig config = new JedisPoolConfig();
    config.setMaxTotal(50);//设置最大连接数量。
    config.setMaxIdle(10);//设置最大空闲连接。
    JedisPool jedisPool = new JedisPool(config, "localhost", 6379);
    Jedis jedis = jedisPool.getResource();
    jedis.close();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值