课堂随笔

文章目录:

 Java语言有4核心部分

方法调用 

类的定义 

继承与接口

正则表达式

如何建立 java web

servlet

File类的使用

对象流的使用

JavaWeb学习总结

转发和重定向

集合框架

泛型

连接数据库


 Java语言有4核心部分

1、面向对象
2、文件I/O流
3、泛型与集合
4、JDBC
      5、线程
      6、网络

方法调用 

在同一个类中:
     1、实例方法,可以调用所有成员(成员变量和成员方法)
     2、静态(类)方法,只能调用静态成员,如果要调用实例成员必须创建对象,用对象来调用
   在不同类中:
     1、一个类中的实例方法,要调用另一个类的实例成员,必须先创建对象,用对象来调用
        一个类中的实例方法,要调用另一个类的静态成员,一般直接使用类名调用,
        也可以创建对象来调用,但是不提倡对象调用

     2、一个类的静态(类)方法,要调用另一个类的实例成员,必须先创建对象,用对象来调用
        一个类中的静态(类)方法,要调用另一个类的静态成员,一般直接使用类名调用,
        也可以创建对象来调用,但是不提倡对象调用

类的定义 

  1、设计类:定义类,包括访问权限(public、缺省)和一般修改符(abstract、final)
        final修改的系统类很多,比如Math、String、System
  2、属性/成员变量/field/域/字段:访问权限  修改符  数据类型  变量名 = 初始化值;
        (1) 访问权限:private 缺省(包访问级)  protected  public
           要使用这些访问权限,有一个前提条件:是这个类能够被访问
        (2) 修改符:static  final
               static:(1) 它修饰成员变量属于整个类所有,不属于某个对象
                       (2) 在类加载的内存中,该变量就分别了存储空间,
                            而实例变量,必须在创建对象后,才分配存储空间
               final:该修改符所修饰成员必须初始化,
                  初始化可以有两种情况来初始化:一种情况定义时初始化,另一种情况是在构造方法中初始化)
        (3) 数据类型:基本数据类型:8种,引用类型(类类型、数组、接口)
  3、方法 /成员方法(行为、操作、功能...)
      访问权限  一般修饰符   数据类型  方法名 ( 参数 )
      (1) 访问权限:private 缺省(包访问级)  protected  public
           要使用这些访问权限,有一个前提条件:是这个类能够被访问
      (2) 修改符:abstract static  final
            final: 修改方法,表示该方法不能在派生的子类中重写/重构/覆盖(override)
            static: 修改方法,表示该方法是一个类方法(静态方法),属于整个类所有,
                     不属于某个对象,一般要使用类名来调用
            abstract:修改方法,该方法不能有方法体,是用分号结束
                      在子类中必须重写该方法,实现该方法
       (3) 数据类型:基本数据类型:8种,引用类型(类类型、数组、接口)
       (4) 参数,参数列表
       (5) 方法重载 overload
           方法相同,参数类型或个数不同
       (6) 特殊方法:构造方法
构造方法:
(1) 构造方法名与类名相同。
(2) 构造方法的作用是给对象赋初值,没有返回值,但不需要用void来指明这一点。
(3) 构造方法不能被程序显式调用,即不应该向其它方法一样来使用构造方法。
(4) 构造方法可以在类中由编程者定义,若编程者没有定义,系统将自动生成一个构造方法(默认构造方法),来完成对象创建时的初始化工作。
(5) 构造方法可以通过重载实现不同的初始化方法。
(6) 构造方法可以用public、protected、private修饰或缺省
(7) 编程者一旦定义了构造方法,就不能再调用默认构造方法。


       
    重载:overload ,一般方法名相同,参数个数或者类型不同
    重构/覆盖:override,只能用在父类与子类,要求方法名,方法参数都完全一样

 直到三角形的三条边求面积

package com.ch4.autority;

import java.util.Scanner;

/*
   a,b,c
   s=(a+b+c)/2
   sqrt(s*(s-a)*(s-b)*(s-c)) 海伦公式
 */
public class Triangle {
    double sideA, sideB, sideC;
    void setSide(double a, double b, double c) {
        sideA = a;
        sideB = b;
        sideC = c;
    }
    double getSideA() {      return sideA;    }
    double getSideB( ) {     return sideB;   }
    double getSideC( ) {      return sideC;   }
    boolean isOrNotTrangle(double sideA,double sideB,double sideC ) {
        if(sideA+sideB>sideC&&sideA+ sideC>sideB&&sideB+ sideC>sideA)
        {
            return true;
        }
        else {
            return false;
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double a,b,c;
        System.out.println("请输入三角形的三边:a,b,c的值");
        a=sc.nextDouble();
        b=sc.nextDouble();
        c=sc.nextDouble();
        double s=(a+b+c)/2;
        Triangle t = new Triangle();
        if(t.isOrNotTrangle(a,b,c)){
           double area = Math.sqrt(s*(s-a)*(s-b)*(s-c));
            System.out.println("三角形的面积为:"+area);
        }else {
            System.out.println("三边长不构成三角形");
        }

    }



}

 显示时间

package com.ch4.autority;

public class Time {
    private int hour;              // 表示小时
    private int minute;            // 表示分钟
    private int second;            // 表示秒
    public Time(){

    }
    public Time(int hour,int minute,int second){
        this.hour = hour;
        this.minute = minute;
        this.second = second;
    }
    public Time(String time){ //  25:70:65
        hour = Integer.parseInt(time.substring(0,2));
        hour = (hour < 0) ? 0 : hour % 24;
        minute = Integer.parseInt(time.substring(3,5));
        minute = (minute < 0) ? 0 : minute % 60;
        second = Integer.parseInt(time.substring(6,8));
        second = (second < 0) ? 0 : second % 60;
    }


    public void setTime(int h, int m, int s) { // 参数为3个int类型
        hour = (h<0) ? 0 : h % 24;
        minute = (m<0)? 0: m % 60;
        second = (s<0)? 0: s % 60;
    }
    public void setTime(String time) {     // 参数为String类对象
        //50:80:65
        hour = Integer.parseInt(time.substring(0,2));
        hour = (hour < 0) ? 0 : hour % 24;
        minute = Integer.parseInt(time.substring(3,5));
        minute = (minute < 0) ? 0 : minute % 60;
        second = Integer.parseInt(time.substring(6,8));
        second = (second < 0) ? 0 : second % 60;
    }
    public int getHour() { return hour; }
    public int getMinute() { return minute; }
    public int getSecond() { return second; }

    public void setHour(int hour) {
        this.hour = hour;
    }

    public void setMinute(int minute) {
        this.minute = minute;
    }

    public void setSecond(int second) {
        this.second = second;
    }

    public void show(){
        System.out.println("hour="+hour+"  minute="+minute+" second="+second);
    }

}
package com.ch4.autority;

public class TestTime {
    public static void main(String[] args) {
       Time t1 = new Time();
       t1.setTime(35,90,80);
       t1.show();
       Time t2 = new Time(23,56,45);
       t2.show();
       Time t3 = new Time("65:85:90");
       t3.show();
    }
}

继承与接口

package com.inter;

public interface Shape {
    double getArea();
    double getzhouchang();
}
package com.inter;

public class Circle implements Shape{
    private double r;
    public Circle() {
    }
    public Circle(double r) {
        this.r = r;
    }
    @Override
    public double getArea() {
        return Math.PI*r*r;
    }

    @Override
    public double getzhouchang() {
        return 2*Math.PI*r;
    }

    public double getR() {
        return r;
    }

    public void setR(double r) {
        this.r = r;
    }
}
package com.inter;

public class Rectangle implements Shape{
    private int width;
    private int height;

    public Rectangle() {
    }

    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }

    @Override
    public double getArea() {
        return width*height;
    }

    @Override
    public double getzhouchang() {
        return 2*(width+height);
    }
}
package com.inter;

public class Triangle implements Shape{
    private int a,b,c;

    public Triangle() {
    }

    public Triangle(int a, int b, int c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public boolean isTriangle(int a,int b,int c){
        if(a+b>c && b+c>a && a+c>b){
          return  true ;
        }
        return  false;
    }

    @Override
    public double getArea() {
        double s =(a+b+c)/2;
        double area =0;
        if(isTriangle(a,b,c)){
            area =Math.sqrt(s*(s-a)*(s-b)*(s-c));
        }else {
            System.out.println("不能构成一个三角形");;
        }
        return area;

    }

    @Override
    public double getzhouchang() {
        return a+b+c;
    }
}
package com.inter;

public class TestShape {
    public static void main(String[] args) {
        Shape []shapes = new Shape[3];
        shapes[0] = new Circle(10);

        shapes[1] = new Rectangle(10,20);
        shapes[2] = new Triangle(3,4,5);
        for(int i=0;i
package e93;

public class Goods implements Comparable{
    private String name;
    private int price;

    public Goods() {
    }

    public Goods(String name, int price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Goods{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    @Override
    public int compareTo(Object o) {
        if(o instanceof Goods){
            Goods goods = (Goods) o;
            if(this.price>goods.price){
                return 1;
            }else if(this.price< goods.price){
                return -1;
            }else {
                //return 0;
               return -this.name.compareTo(goods.name);
            }
        }
        return 0;
    }
}
package e93;

import java.util.Arrays;

public class TestCompare {
    public static void main(String[] args) {
        String [] a={"boy","apple","Applet","girl","Hat"};
        Arrays.sort(a);
        System.out.println(Arrays.toString(a));
        Goods [] goods =new Goods[5];
        goods[0] = new Goods("levoMouse",20);
        goods[1] = new Goods("huaweiMouse",55);
        goods[2] = new Goods("axiaomiMouse",30);
        goods[3] = new Goods("appleMouse",40);
        goods[4] = new Goods("dellMouse",30);
        Arrays.sort(goods);
        System.out.println(Arrays.toString(goods));
    }
}

public class Goods implements Comparable, Comparator

正则表达式

见文档 

如何建立 java web

IntelliJ IDEA 2020.3.1 版本 如何建立 java web?

1、Java Application 由main来运行
2、Java Applet  Application let    //浏览器来运行
3、Java Servlet  Server let   //由服务器来运行

servlet

见文档 

File类的使用

package com.file;

import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * File类的使用
 *
 * 1. File类的一个对象,代表一个文件或一个文件目录(俗称:文件夹)
 * 2. File类声明在java.io包下
 * 3. File类中涉及到关于文件或文件目录的创建、删除、重命名、修改时间、文件大小等方法,
 *    并未涉及到写入或读取文件内容的操作。如果需要读取或写入文件内容,必须使用IO流来完成。
 * 4. 后续File类的对象常会作为参数传递到流的构造器中,指明读取或写入的"终点".
 *
 *
 *
 *
 * @author shkstart
 * @create 2019 下午 4:05
 */
public class FileTest {
    /*
    1.如何创建File类的实例
        File(String filePath)
        File(String parentPath,String childPath)
        File(File parentFile,String childPath)

    2.
    相对路径:相较于某个路径下,指明的路径。
    绝对路径:包含盘符在内的文件或文件目录的路径

    3.路径分隔符
     windows:\\
     unix:/
     */
    @Test
    public void test1(){
        //构造器1
        File file1 = new File("hello.txt");//相对于当前module
        File file2 =  new File("D:\\workspace_idea1\\JavaSenior\\day08\\he.txt");

        System.out.println(file1);
        System.out.println(file2);

        //构造器2:
        File file3 = new File("D:\\workspace_idea1","JavaSenior");
        System.out.println(file3);

        //构造器3:
        File file4 = new File(file3,"hi.txt");
        System.out.println(file4);
    }

    /*
public String getAbsolutePath():获取绝对路径
public String getPath() :获取路径
public String getName() :获取名称
public String getParent():获取上层文件目录路径。若无,返回null
public long length() :获取文件长度(即:字节数)。不能获取目录的长度。
public long lastModified() :获取最后一次的修改时间,毫秒值

如下的两个方法适用于文件目录:
public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组
public File[] listFiles() :获取指定目录下的所有文件或者文件目录的File数组


     */
    @Test
    public void test2(){
        File file1 = new File("hello.txt");
        File file2 = new File("d:\\io\\hi.txt");

        System.out.println(file1.getAbsolutePath());
        System.out.println(file1.getPath());
        System.out.println(file1.getName());
        System.out.println(file1.getParent());
        System.out.println(file1.length());
        System.out.println(new Date(file1.lastModified()));

        System.out.println();

        System.out.println(file2.getAbsolutePath());
        System.out.println(file2.getPath());
        System.out.println(file2.getName());
        System.out.println(file2.getParent());
        System.out.println(file2.length());
        System.out.println(file2.lastModified());
    }
    @Test
    public void test3(){
        File file = new File("D:\\workspace_idea1\\JavaSenior");

        String[] list = file.list();
        for(String s : list){
            System.out.println(s);
        }

        System.out.println();

        File[] files = file.listFiles();
        for(File f : files){
            System.out.println(f);
        }

    }
    /*
    public boolean renameTo(File dest):把文件重命名为指定的文件路径
     比如:file1.renameTo(file2)为例:
        要想保证返回true,需要file1在硬盘中是存在的,且file2不能在硬盘中存在。
     */
    @Test
    public void test4(){
        File file1 = new File("hello.txt");
        File file2 = new File("D:\\io\\hi.txt");

        boolean renameTo = file2.renameTo(file1);
        System.out.println(renameTo);

    }
    /*
public boolean isDirectory():判断是否是文件目录
public boolean isFile() :判断是否是文件
public boolean exists() :判断是否存在
public boolean canRead() :判断是否可读
public boolean canWrite() :判断是否可写
public boolean isHidden() :判断是否隐藏

     */
    @Test
    public void test5(){
        File file1 = new File("hello.txt");
        file1 = new File("hello1.txt");

        System.out.println(file1.isDirectory());
        System.out.println(file1.isFile());
        System.out.println(file1.exists());
        System.out.println(file1.canRead());
        System.out.println(file1.canWrite());
        System.out.println(file1.isHidden());

        System.out.println();

        File file2 = new File("d:\\io");
        file2 = new File("d:\\io1");
        System.out.println(file2.isDirectory());
        System.out.println(file2.isFile());
        System.out.println(file2.exists());
        System.out.println(file2.canRead());
        System.out.println(file2.canWrite());
        System.out.println(file2.isHidden());

    }
    /*
    创建硬盘中对应的文件或文件目录
public boolean createNewFile() :创建文件。若文件存在,则不创建,返回false
public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。如果此文件目录的上层目录不存在,也不创建。
public boolean mkdirs() :创建文件目录。如果此文件目录存在,就不创建了。如果上层文件目录不存在,一并创建

    删除磁盘中的文件或文件目录
public boolean delete():删除文件或者文件夹
    删除注意事项:Java中的删除不走回收站。

     */
    @Test
    public void test6() throws IOException {
        File file1 = new File("hi.txt");
        if(!file1.exists()){
            //文件的创建
            file1.createNewFile();
            System.out.println("创建成功");
        }else{//文件存在
            file1.delete();
            System.out.println("删除成功");
        }


    }
    @Test
    public void test7(){
        //文件目录的创建
        File file1 = new File("d:\\io\\io1\\io3");

        boolean mkdir = file1.mkdir();
        if(mkdir){
            System.out.println("创建成功1");
        }

        File file2 = new File("d:\\io\\io1\\io4");

        boolean mkdir1 = file2.mkdirs();
        if(mkdir1){
            System.out.println("创建成功2");
        }
        //要想删除成功,io4文件目录下不能有子目录或文件
        File file3 = new File("D:\\io\\io1\\io4");
        file3 = new File("D:\\io\\io1");
        System.out.println(file3.delete());
    }
}

对象流的使用

ObjectInputOutputStreamTest.java 

package com.atguigu.java;

import org.junit.Test;

import java.io.*;

/**
 * 对象流的使用
 * 1.ObjectInputStream 和 ObjectOutputStream
 * 2.作用:用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。
 *
 * 3.要想一个java对象是可序列化的,需要满足相应的要求。见Person.java
 *
 * 4.序列化机制:
 * 对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种
 * 二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。
 * 当其它程序获取了这种二进制流,就可以恢复成原来的Java对象。

 *
 * @author shkstart
 * @create 2019 上午 10:27
 */
public class ObjectInputOutputStreamTest {

    /*
    序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去
    使用ObjectOutputStream实现
     */
    @Test
    public void testObjectOutputStream(){
        ObjectOutputStream oos = null;

        try {
            //1.
            oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
            //2.
            oos.writeObject(new String("我爱北京天安门"));
            oos.flush();//刷新操作

            oos.writeObject(new Person("王铭",23));
            oos.flush();

            oos.writeObject(new Person("张学良",23,1001,new Account(5000)));
            oos.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(oos != null){
                //3.
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

    }

    /*
    反序列化:将磁盘文件中的对象还原为内存中的一个java对象
    使用ObjectInputStream来实现
     */
    @Test
    public void testObjectInputStream(){
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("object.dat"));

            Object obj = ois.readObject();
            String str = (String) obj;

            Person p = (Person) ois.readObject();
            Person p1 = (Person) ois.readObject();

            System.out.println(str);
            System.out.println(p);
            System.out.println(p1);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(ois != null){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }



    }

}

Person.java 

package com.atguigu.java;

import java.io.Serializable;

/**
 * Person需要满足如下的要求,方可序列化
 * 1.需要实现接口:Serializable
 * 2.当前类提供一个全局常量:serialVersionUID
 * 3.除了当前Person类需要实现Serializable接口之外,还必须保证其内部所有属性
 *   也必须是可序列化的。(默认情况下,基本数据类型可序列化)
 *
 *
 * 补充:ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
 *
 *
 * @author shkstart
 * @create 2019 上午 10:38
 */
public class Person implements Serializable{

    public static final long serialVersionUID = 475463534532L;

    private String name;
    private int age;
    private int id;
    private Account acct;

    public Person(String name, int age, int id) {
        this.name = name;
        this.age = age;
        this.id = id;
    }

    public Person(String name, int age, int id, Account acct) {
        this.name = name;
        this.age = age;
        this.id = id;
        this.acct = acct;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", id=" + id +
                ", acct=" + acct +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    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 Person(String name, int age) {

        this.name = name;
        this.age = age;
    }

    public Person() {

    }
}

class Account implements Serializable{
    public static final long serialVersionUID = 4754534532L;
    private double balance;

    @Override
    public String toString() {
        return "Account{" +
                "balance=" + balance +
                '}';
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public Account(double balance) {

        this.balance = balance;
    }
}

ServletVerifyCode.java 

package com.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/code")
public class ServletVerifyCode extends HttpServlet {
    private static  final int width=120;
    private static  final int height=25;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedImage image =new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        //设置背景颜色
        setBackGround(g);
        //设置边框颜色
        setBorder(g);
        //设置干扰线
        drawRandowLine(g);
        //写随机数
        String code=drawRandowNumer((Graphics2D)g);
        req.getSession().setAttribute("code",code);

        resp.setContentType("image/jpeg");
        resp.setDateHeader("expries",-1);
        resp.setHeader("Cache-Control","no-cache");
        resp.setHeader("Pragma","no-cache");
        ImageIO.write(image,"jpg",resp.getOutputStream());
    }




    private void setBackGround(Graphics g) {
        int r =new Random().nextInt(255);
        int g1 =new Random().nextInt(255);
        int b =new Random().nextInt(255);
        Color c =new Color(r,g1,b);

        g.setColor(c);
        g.fillRect(0,0,width,height);
    }
    private void setBorder(Graphics g) {
        g.setColor(Color.BLUE);
        g.drawRect(1,1,width-2,height-2);
    }
    private void drawRandowLine(Graphics g) {
        g.setColor(Color.GREEN);
        for(int i=0;i<5;i++){
            int x1= new Random().nextInt(width);
            int y1= new Random().nextInt(height);
            int x2= new Random().nextInt(width);
            int y2= new Random().nextInt(height);
            g.drawLine(x1,y1,x2,y2);
        }
    }

    private String drawRandowNumer(Graphics2D g) {
        g.setColor(Color.RED);
        g.setFont(new Font("宋体",Font.BOLD,20));
        String base="\u7684\u4e00\u4e86\u662f\u6211\u4e0d\u5728\u4eba\u4eec\u6709\u6765\u4ed6\u8fd9\u4e0a\u7740\u4e2a\u5730\u5230\u5927\u91cc\u8bf4\u5c31\u53bb\u5b50\u5f97\u4e5f\u548c\u90a3\u8981\u4e0b\u770b\u5929\u65f6\u8fc7\u51fa\u5c0f\u4e48\u8d77\u4f60\u90fd\u628a\u597d\u8fd8\u591a\u6ca1\u4e3a\u53c8\u53ef\u5bb6\u5b66\u53ea\u4ee5\u4e3b\u4f1a\u6837\u5e74\u60f3\u751f\u540c\u8001\u4e2d\u5341\u4ece\u81ea\u9762\u524d\u5934\u9053\u5b83\u540e\u7136\u8d70\u5f88\u50cf\u89c1\u4e24\u7528\u5979\u56fd\u52a8\u8fdb\u6210\u56de\u4ec0\u8fb9\u4f5c\u5bf9\u5f00\u800c\u5df1";
        //String base="0123456789abcdefghijkABCDEFGHIJKLMN";

        int x=5;
        StringBuilder sb =new StringBuilder();
        for(int i=0;i<4;i++){
           String ch= base.charAt(new Random().nextInt(base.length()))+"";
           sb.append(ch);
           int degree = new Random().nextInt()%30;
           g.rotate(degree*Math.PI/180,x,20);
           g.drawString(ch,x,20);
           g.rotate(-degree*Math.PI/180,x,20);
           x+=30;
        }
        return sb.toString();
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

 RegisterServlet.java

package com.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/reg")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String vercode = req.getParameter("vercode").trim();
        String code = (String) req.getSession().getAttribute("code");
        if(vercode!=null && code!=null && vercode.equalsIgnoreCase(code)){
            System.out.println("验证码成功");
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

JavaWeb学习总结

 JavaWeb学习总结   孤傲苍狼

转发和重定向

1.重定向至少发出两次,而转发只有一次请求
2.重定向是浏览器端进行,而转发是在服务器端进行
3.重定向地址栏会发生改变,而转发地址栏种,地址不发生改变
4.重定向到下一个页面,不能传递数据过去,而转发会把数据传递到下一个页面中
5.重定向可以重定向到其他网站,而转发只能在当前项目
6.代码不同

集合框架

见文档 

ider激活

http://lookdiv.com/
5263

泛型

见PPT

连接数据库

建立数据库表

CREATE DATABASE `testjdbc` ;

USE `testjdbc`;

DROP TABLE IF EXISTS `customers`;

CREATE TABLE `customers` (
  `id` INT(10) NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(15) DEFAULT NULL,
  `email` VARCHAR(20) DEFAULT NULL,
  `birth` DATE DEFAULT NULL,
  `photo` MEDIUMBLOB,
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;



INSERT  INTO `customers`(`id`,`name`,`email`,`birth`,`photo`) VALUES 
         (1,'汪峰','[email protected]','2010-02-02',NULL),
	 (2,'王菲','[email protected]','1988-12-26',NULL),
	 (3,'林志玲','[email protected]','1984-06-12',NULL),
	 (4,'汤唯','[email protected]','1986-06-13',NULL),
	 (5,'成锟','[email protected]','1955-07-14',NULL),
	 (6,'迪丽热巴','[email protected]','1983-05-17',NULL),
	 (7,'刘亦菲','[email protected]','1991-11-14',NULL),
	 (8,'陈道明','[email protected]','2014-01-17',NULL),
	 (10,'周杰伦','[email protected]','1979-11-15',NULL),
	 (12,'黎明','[email protected]','1998-09-08',NULL),
	 (13,'张学友','[email protected]','1998-12-21',NULL),
	 (16,'朱茵','[email protected]','2014-01-16',NULL);
	 



DROP TABLE IF EXISTS `examstudent`;

CREATE TABLE `examstudent` (
  `FlowID` INT(20) NOT NULL AUTO_INCREMENT,
  `Type` INT(20) DEFAULT NULL,
  `IDCard` VARCHAR(18) DEFAULT NULL,
  `ExamCard` VARCHAR(15) DEFAULT NULL,
  `StudentName` VARCHAR(20) DEFAULT NULL,
  `Location` VARCHAR(20) DEFAULT NULL,
  `Grade` INT(10) DEFAULT NULL,
  PRIMARY KEY (`FlowID`)
) ENGINE=INNODB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;




INSERT  INTO `examstudent`(`FlowID`,`Type`,`IDCard`,`ExamCard`,`StudentName`,`Location`,`Grade`) VALUES 
              (1,4,'412824195263214584','200523164754000','张锋','北京',85),
	      (2,4,'222224195263214584','200523164754001','孙朋','上海',56),
	      (3,6,'342824195263214584','200523164754002','刘明','天津',72),
	      (4,6,'100824195263214584','200523164754003','赵虎','重庆',95),
	      (5,4,'454524195263214584','200523164754004','杨丽','成都',64),
	      (6,4,'854524195263214584','200523164754005','王小红','广州',60);



DROP TABLE IF EXISTS `order`;

CREATE TABLE `order` (
  `order_id` INT(10) NOT NULL AUTO_INCREMENT,
  `order_name` VARCHAR(20) DEFAULT NULL,
  `order_date` DATE DEFAULT NULL,
  PRIMARY KEY (`order_id`)
) ENGINE=INNODB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

INSERT  INTO `order`(`order_id`,`order_name`,`order_date`) VALUES 
           (1,'AA','2010-03-04'),
	   (2,'BB','2000-02-01'),
	   (2,'CC','2001-03-01'),
	   (4,'GG','1994-06-28');




DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(10) NOT NULL,
  `password` VARCHAR(15) NOT NULL DEFAULT '123456',
  `address` VARCHAR(25) DEFAULT NULL,
  `phone` VARCHAR(15) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

INSERT  INTO `user`(`id`,`name`,`password`,`address`,`phone`) VALUES 
       (1,'张虹','qwerty','Beijing','13788658672'),
       (2,'李丽','abc123','HongKong','15678909898'),
       (3,'汪萍','654321','Taiwan','18612124565'),
       (4,'李渊','987654367','malaixiya','18912340998'),
       (5,'封疆','123456','America','13012386565');



DROP TABLE IF EXISTS `user_table`;

CREATE TABLE `user_table` (
  `user` VARCHAR(20) DEFAULT NULL,
  `password` VARCHAR(20) DEFAULT NULL,
  `balance` INT(20) DEFAULT NULL
) ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT  INTO `user_table`(`user`,`password`,`balance`) VALUES 
                 ('AA','123456',1000),
	         ('BB','654321',1000),
	         ('CC','351236',2000),
	         ('DD','239678',3000);
package com.jdbc;

import org.junit.Test;

import java.sql.*;
import java.util.Properties;

public class TestJDBC {

    @Test
    public void test1() {
        // 获取Driver实现类对象
        //1.提供java.sql.Driver接口实现类的对象
        Driver driver=null;
        Connection conn=null;
        PreparedStatement ps =null;
        ResultSet rs =null;
        try {
            driver=new com.mysql.jdbc.Driver();//使用mysql数据库驱动类实现
            String url="jdbc:mysql://localhost:3306/testjdbc";
            /bc:sqlserver://IP:1433;databasename=testjdbc
            /bc:oracle:fds
            Properties info = new Properties();
            info.setProperty("user", "root");//user是固定写法
            info.setProperty("password", "123456");//password是固定写法

            conn =driver.connect(url,info);
            String sql="select * from customers where id>?";
            ps = conn.prepareStatement(sql);

            ps.setInt(1,5);
            rs = ps.executeQuery();
            while (rs.next()){
                int id=rs.getInt("id");
                String name = rs.getString("name");
                String email = rs.getString("email");
                Date date =rs.getDate("birth");
                System.out.print(id +"\t"+name+"\t"+"\t"+email+"\t"+date);
                System.out.println();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(ps!=null){
                try {
                    ps.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }


    }

}
@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setAttribute("name","zhangsan");
        //request.getRequestDispatcher("/s2").forward(request,response);
       // request.getRequestDispatcher("st.jsp").forward(request,response);

        RequestDispatcher requestDispatcher=request.getRequestDispatcher("st.jsp");
        requestDispatcher.forward(request,response);

       /* response.setStatus(302);
        response.setHeader("location","s2");*/
       // response.sendRedirect(request.getContextPath()+"/s2");

       // response.sendRedirect(request.getContextPath()+"st.jsp");

        /*




         */


    }



    
    文件上传


  
文件上传1:
文件上传2:
文件上传3:
package com.servlet;

import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;



@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 request.setCharacterEncoding("utf-8");
		 //Tomcat 7.x
			/*
			  Part part = request.getPart("file1"); 
			  //System.out.println(part.getName());
			  String uploadPath = this.getServletContext().getRealPath("/upload"); 
			  String header = part.getHeader("content-disposition"); 
			  System.out.println(header);
			  int index = header.lastIndexOf("=")+2; String
			  filename=header.substring(index,header.length()-1);
			  System.out.println(filename); part.write(uploadPath+"/"+filename);
			
	        //Tomcat 8及其以后写法
		    Part part = request.getPart("file1");
	        //System.out.println(part.getName());
	        String uploadPath = this.getServletContext().getRealPath("/upload");
	        String filename =part.getSubmittedFileName();
	        System.out.println(filename);
	        part.write(uploadPath+"/"+filename);
	         */
		 //多个文件上传
		 String uploadPath = this.getServletContext().getRealPath("/upload");
		 Collection parts = request.getParts();
		 for(Part part:parts) {
			 if(part.getName().startsWith("file")) {
				 String fileName = part.getSubmittedFileName();
				 part.write(uploadPath+"/"+fileName);
			 }
		 }
		 

	}

}
<%@ page language="java" contentType="textml; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


<%=request.getContextPath() %>

<%--
--%> 姓名:
密码:

xxx
图片不能显示
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setAttribute("name", "zhangsan");
		/tp://localhost:8088/PathProject
		/tp://localhost:8088/PathProject
		request.getRequestDispatcher("/s2").forward(request, response);
		
		//response.sendRedirect(request.getContextPath()+"/s2");
		response.sendRedirect("s2");
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(#,JAVA)