JAVA 笔记

原来的JAVA没学好啊~~惭愧~~囧。。
11月30日

1.JAVA安装
java_home:java安装路径 jdk
path:JAVA编译解释路径  jdk/bin
classpath:类路径  .;jre/lib
2.helloworld
 d:  cd
 编译:javac helloworld.java
 解释:java helloworld
3.在src中建公文包,收费:com.公司名.项目名.jbs/不收费org.

12月1日

1.标识符:以字母、下划线、"$"开头。
2.java是强类型语言。(所有的变量都必须显示声明类型)
3.java分为两大类型:简单(原始)数据类型和引用类型。
boolean 1    byte 8  char 16  short 16   int 32  float 32  long 64  double 64
4.整形:byte int short long .
5.类型一致才能计算。短整形、浮点型可以自动向长整形、浮点型转换。
例:short a=1;
    short c=(short) (a+1);
 1)两种类型兼容。2)目标类型要大于原始类型。默认:int、double.
 表达式:表达式中最大类型式long,则表达式提升为long型。
6.引用类型:类、接口、数组。
7.类类型:Student s1;
          s1=new Student("hdj",23);
  1)系统在栈中为s1分配内存。s1:null
  2)碰到new时在堆中为s1的属性分配内存。
    name :null
    age  :0
    sex  :null
    grade:0
  3)调用构造器。this.name=name,this.age,this.sex,this.grade.
  4)地址转换:name:0x1234   s1:0x1234。
8.全局变量有默认初始值,使用可以不用初始化。
  局部变量没有默认初始值,在使用之前必须初始化。
9.实参可以传给形参,形参不能传给实参(值传递)。
10.String s=new String("abc");(创建了两个对象)
   String s="abc";(创建了一个对象)
11.类顺序:属性、构造器、set.get方法,其他方法。
12.接口首字母大写,方法、变量首字母小写2单词字母大写,常量大写。
13.数组(Array)  String[] args;int[] a;
14.for循环里面定义的变量只能在for中有效。
15.j=++i先加1再赋值,j=i++先赋值再加1。
16.&与运算符,~非,|或运算符.
17.a+=2等于a=a+2.
18.int a=2;
   a=a<<2;(左移)

                                       
12月7日上午

1、2.0是double类型。5/2.0=2.5,5/2=2。
2、==,!=可用于对象的比较。
3、5+“abc”=“5abc”。
4、switch(n),n是int型。switch(2++)相当于switch(3)。
5、while(true){};死循环,服务器。
6、for(;i<100;i++).
7、循环的作用:让程序按顺序执行。
8、return是直接退出函数,后面的程序不会执行。
9、break跳出整个循环体,continue结束当前循环,进入下个循环。
10、0%2=0;
11、int[] a = new int[5];
12、int[] a = new int[]{3,4,5}静态初始化。
13、动态初始化:int[] a;
                a=new int[4];
                for(int i=0;i<4;i++)
                {
                   a[i] = 2*i+8;
                }
14、Arrays.sort();
    Math.random();产生0到1的随机数。
15、System.arraycopy(a,4,b,0,5);索引值。
作业:
1、0到100产生任意数的数组,用冒泡和快速排序进行排序。
2、学生类,10个,按工资排序,从高到低输出工资并打印出名字。
3、求任意数的阶乘。
4、用switch语句实现根据int i;的值(0到9,10到99,100-999)调用不同的方法do0_9(),do10_99(),do100_999().


12月8日

1、面向对象的的特点:数据封装、继承、多态。
2、类的构造器不能被重写,可以被重载,不能被继承。
3、面向对象最重要的特点之一是可以实现对类的复用。
4、1个类只能继承一个父类。
5、object类:任何类都是object的子类。
6、如果子类和父类不在同一个包中,子类不能继承父类的友好成员。在同一个包中,子类可以继承父类友好成员。
不管子类和父类在不在同一个包中,子类都继承父类的受保护的和公共的成员,都不能继承私有成员。
7、方法覆盖(重写)后要调用父类的方法时用关键字super. 方法。                    
8、覆盖要具有相同的方法名称、输入参数和返回值。
9、子类中的覆盖方法不能使用比父类更严格的访问权限。
10、this.方法,this可省略。方法直接可相互使用。
11、super的追溯不仅限于直接父类。
12、子类的构造方法创建一个子类对象时,子类的构造方法总是先调用父类的某个构造器。
13、构造器调用构造器用this(),放在程序的最前面,子类调用父类构造器用super()。
14、子类没有显式调用父类构造器时,就自动调用父类无参构造器。
15、{age=18;name="java33";}初始化块,放在属性后面,初始化块中的语句在构造器中语句执行之前执行,初始化一次。
16、方法重载返回类型可以不一样。
17、碰到new就给属性分配内存、初始化块、再调用构造器。
18、==和equals(),对象用==比较时比较的是内存地址。
19、整形变字符串:
    Integer i= new Integer(10);
    int s=i.intValue();
    i.toString();
20、字符串变int型:
   int a=Integer.parseInt("5");
21、一般的两个对象不可能==,重写Object中的equals()方法,如果两个对象的属性相等就返回真。
22、String类中已经覆盖了Object中的equals()方法,两个字符串内容相同就返回真。
23、String类不能被继承。
24、super.x = 100;super.play();就是操作被子类隐藏的变量x和方法play()。
当通过super调用被隐藏的方法play()时,该方法中出现的x是指被隐藏的x。
作业:
  1、覆盖和重载程序练习,覆盖和重载文档。
  2、子类对象的创建过程写文档,person和teacher类。
  3、==、equals、toString的使用。
  4、折半查找法。
  5、PDF上的两道题。

12月10日

1、静态初始化static{}:只在类加载的时候加载一次,通常用于初始化静态变量。
   而普通的初始化块{}在new之后构造器之前执行。
2、静态变量和方法在类加载时就分配内存。(类属性和类方法)
3、构造器不能用static修饰。
   实例方法可以调用该类中的实例方法或类方法,类方法只能调用该类的类方法,不能调用实例方法,实例方法可以操作实例变量或类变量,
   而类方法只能操作类变量,不能操作实例变量。
4、单子模式(singleton):整个类只能有一个实例,定义一个类类型的静态变量。(例Shoes.java)
5、final类不能被继承,final类是最终类,String和Math是final类,final方法不能被覆盖(重写)。
6、final修饰原始类型变量时,在初始化后不能改变变量的值。
7、final修饰引用类型变量时,不能改变它的引用变量,但可以改变对象的属性。
8、abstract类不能被实例化。
9、可以用abstruct修饰类和方法,叫抽象类和抽象方法。
10、抽象方法只有方法的声明,而没有方法的实现。
11、在以下任何一个条件成立时,类必须定义成抽象类:
   1)类中有至少一个抽象方法。
   2)类继承了父类的抽象方法,但有至少一个抽象方法没有被实现。
   3)类实现了某个接口,但没有全部实现接口中的方法。
12、接口只有方法和常量值。
13、接口弥补了java的单继承的不足。
14、接口常量的定义:(public static final) int FGY = 10;
    (public  abstract) void exchange();
15、类实现接口,接口可以继承接口。接口定义:修饰符 interface 名字。
16、父类的引用指向子类的实例就是多态,接口变量指向实现类实例也叫多态。
17、子类方法覆盖父类方法,父类引用指向子类实例调用的是子类方法。
18、子类变量隐藏父类变量,父类引用指向子类实例调用的是父类变量。
19、一个引用类型变量如果声明为父类类型,但实际引用的是子类对象,那么该变量就不能再访问子类中添加的属性和方法。
20、一个对象只能有一种确切的数据类型。
21、一个接口可以继承多个父类接口。
22、类在实现接口方法时一定要用public来修饰,接口中的方法默认是public abstract可以省略。
    接口中的属性默认值是public static final 可以省略。
23、类实现的接口方法和接口中的常量可以被类的对象调用。
24、接口不能实例化但可以声明接口变量,接口回调。
25、接口中只有常量和抽象方法。

12月11日
 
1、if(p instanceof Man)
   {
       Man man= (Man) p;
   }
2、RuntimeException
  ArithmeticException:数学计算异常
  NullPointerException: 空指针异常
  NegativeArraySizeException:负数组长度异常
  ArrayOutOfBoundsException:数组索引越界异常
  ClassNotFoundException:类文件未找到异常
  ClassCastException:造型异常
  IOException
  FileNotFoundException:文件未找到异常
  EOFException:读写文件尾异常
  MalfformedURLException:URL格式错误异常
  SocketException:Socket异常
3、 f6.f5调试。
4、IOException编译不通过,RuntimeException编译通过,运行时报错。
5、出现异常后,异常处后面的程序不会执行。
6、出现异常后,马上交给java虚拟机执行。
7、抛出异常退出程序之前会无条件的执行finaly语句块。[finaly{语句}]。
8、覆盖方法抛出的异常,可以抛出与被覆盖方法的相同的异常或者被覆盖方法的异常的子类异常。
9、主动抛出异常用throw。
10、对象造型分为两类:自动造型和强制造型,对象的造型只用在有继承关系的对象之间。
11、内部类对其封装类的内部私有属性和方法有访问权限。
12、外部类不能设置为私有的、受保护的、静态的,内部类可以设置成私有的或者受保护的和静态的。
13、实例化内部类的两中方法:
1)Outer.Inter in = new Outer().new Inter();
2)Outer o = new Outer();
  Outer.Inter I = o.new Inter();
14、如果内部类是static,也可以这样定义:
  Outer.Inter j = Outer.new Inter();
15、内部类的名字只有在定义的范围内使用,除非使用有效的全名。
16、内部类也可以定义在方法的内部。方法中的final类型的局部变量都可以被内部类的方法访问。
17、内部类可以声明为static的,但此时就不能再使用外层封装类的非static的成员变量。
18、非static的内部类中的成员不能声明为static的,只有在顶层类或static内部类中才可声明static成员。
19、内部类可以声明为抽象类,因此可以被其他的内部类继承,也可以声明为final的。
20、一个类不能即被声明为final又被声明为abstract。
21、匿名类不类一般只能有一个抽象方法。

12月12日

1、作业1:兔子问题(兔子生兔子)。
2、静态方法不能调用实例变量,因为实例变量在类加载时没有分配内存空间。
3、System.exit(0);退出。
4、作业2:写一个属性文件,读出来。
5、System.in读字节。
6、BufferedReader读行。
7、inputstream读字符。
8、作业3:从键盘读3个数字比较大小。
9 、 Scanner的用法。
10、Math.round()需要四舍五入返回long型,math.ceil()(负数取整)和math.floor()(正数取整)直接去掉小数。
11、Math.min(),math.max(),math.sqrt(),math.pow(),math.abs(),math.pI,math.e。
12、作业4:写程序使用Math类中的函数。
13、“abc”是String类型的直接数。
14、作业5:练习使用String类中的各种方法。
15、s.concat("abc").concat("zhong guo");s.replaceAll("a","n");s.substring(0);s.substring(3,4);s.trim();s.trim().toUpperCase();s.indexOf("a")返回-1表示没有找到;a字符第一次出现的位置。s.lastIndexOf("a");最后一次出现的位置。
16、s.substring(2,4);从2开始截取到4之前的字符为止创建一个子串不包括4,从0开始数.
17、String[] strs = s.split("a");让a切割字符串s。
18、中文一个字是两个字节,英文是一个字节。s.getbytes().length!=s.length()表示有中文;
19、作业6:“http://localhost:8080/LCRMS/resumeAdd.do/"取出resumeAdd字符串。
20、prperties类实现了从名字到值的映射。
21、propertyNames()返回一个包含所有属性名的Enumeration对象。
22、getProperty(String  prop_name)返回一个代表该属性值的字符串。
23、String s = "absdf";
    byte[] str = s.getBytes();
    char[] str1 = s.toCharArray();
24、使用load(FileInputStream fis)从文件读入属性集,使用store(FileOutputStream fis)将属性集写入文件.
26、properities 在java.util包中。


12月15日
 
1、辅音:
  清辅音:p,t,k,s,Q,r .两个清音或浊音在一起时后面的音要变成反音,辅音结尾/元音开头要连读。school学院。
  浊音:  b,d,g,z, ,l.
2. good morning!It is my honor to be here for your interview. Now I will introduce myself briefly.
   I am an undergraduate from wuhan college of science and technology.I will get my bachelor's degree in
Computer Science and Technology next July. I am eager to join your company with a resolution to put my
professional skills into practice and create a win-win situation.my name is Hu Dongjie. born and bride in
HuBei province.
   sofewire engineering.
   The four-year university life has acquainted me with the basic knowledge.
   That's all.Thank you for your attention.
   Character and hobby.性格和爱好.
   性格:character,personality,trait
   优点:strong points,strengths,merits,advantage
   缺点:disadvantage
   open-minded 开明的;introvert/extrovert外向/内向;easy-going 随和的;mature and stable成熟稳重的;
   reasonable and calm 理智冷静的;Optimistic乐观的
   I don't like leaving thing half done.
   I wouldn't call myself introverted though sometimes I'm resweved and enjoy staying all by myself,often and
   often I like sharing activtis with other.I get on well with others.
3、Collection顶级接口(集合):List有序可重复子接口,Set无序不可重复子接口。
4、ArrayList类是List接口的一个可变长数组实现。(动态数组)
   ArrayList中的函数有:
   public int size();//返回列表中的元素个数
   public Object get(int index);//返回指定位置的元素
   public void set(int index,Object obj);//设置指定位置元素
   public void add(Object obj);//在列表末尾增加元素
   public void add(int index,Object obj);//在列表指定位置插入元素
   public void remove(int index);//删除列表中指定位置元素
   public void clear();//删除列表中的所有元素
   public boolean contains(Object obj);//判断列表中指定对象是否存在
5、List list = new ArrayList();
   Iterator<> its = list.iterator();
   while(its.hasNext()){
        System.out.print(its.next());
   }
6、List、ArrayList里面装的全部是Object对象,所以类对象要先强制转换成该类对象。
   Student  stu = (Student) its.next();
   System.out.println(stu.getAge());
7、泛型1.5才支持,List<Student> list = new ArrayList<Student>(); 此时就不需要强制转换了。
8、Set set = new HashSet();
   Iterator<> its = set.iterator();
   while(its.hasNext()){
        System.out.print(its.next());
   }
9、List:ArrayList,Vector,LinkedList.
10、StringBuffer类:
    StringBuffer sb = new StringBuffer();
    sb.append(true).append(34.6).append("hdj").append(3);
    System.out.println(sb.toString());
    System.out.println(sb.reverse().toString());反转输出(3hdj34.6true).
11、文件:File 类,File.seperator自动打斜杠。包括文件和文件夹。
12、创建文件:
    File file1 = new File("F:/file/abx.txt");
或者File file1 = new File("F:/file","abx.txt");
或者File file = new File("F:/file");File file1 = new File(file,"a.txt");  
    if(!file1.exists()){
         file1.createNewFile();
    }
13、创建文件夹:
    String path = "F:/file/abc/cde";
    File file = new File(path);
     if(!file.exists()){
         file.mkdir();
    }
14、length()返回多少个字节。
15、lastModified()最后一次修改时间。
16、剪切:
    File file1 = new File("F:/file/ax.txt");
    File file2 = new File("F:/file/abc/ax.txt");
    file1.renemeTo(file2);
17、获取文件路径:
    System.out.println(file2.getParent());
    System.out.println(file2.getName());
    System.out.println(file2.lastModified());
    System.out.println(file2.getParent());
    System.out.println(file2.length());

19、作业:把某个文件夹中后缀名为txt的文件全部剪切走。
    判断后缀名是不是txt:
    File desFile = new File(des,fileArr[i].getName());
20、listFiles()函数返回File数组。
21、file.isFile()判断是不是数组,返回boolean类型。
22、作业:把一个文件夹里面的所有的东西剪切到另外一个文件夹中。
23、map:HashMap;映射。
    Map map = new HashMap();
    map.put("1",new Student("123",22));
    map.put("2",new Student("123",22));
    map.put(null,new Student("233",23));
    map.put("4",null);
    Student stu = (Student)map.get("2");
    Map<String ,Student> map = new HashMap<String,Student>();
    Student stu = map.get("2");
    Set set = map.keySet();
24、hashtable(key和value)不允许null值,hashmap(key和value)允许null,hashtable的方法是同步的,hashmap是未经同步的。
25、Iterator拿一个少一个。
26、中文字节的值大于127和小于0。

12月16日

1、  Date类以1970 1.1 为开始时间过了多少毫秒。
2、  long getTime()
          返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
     void setTimeInMillis(long millis)
          设置此 Date 对象,以表示 1970 年 1 月 1 日 00:00:00 GMT 以后 time 毫秒的时间点。
     setTime(Date date)
          使用给定的 Date 设置此 Calendar 的时间。
     String toString()
          把此 Date 对象转换为以下形式的 String: dow mon dd hh:mm:ss zzz yyyy 其中:
          dow 是一周中的某一天 (Sun, Mon, Tue,  Wed, Thu, Fri, Sat)。 
     boolean after(Date when)
          测试此日期是否在指定日期之后。
     boolean before(Date when)
          测试此日期是否在指定日期之前。
     Object clone()
          返回此对象的副本。
     int compareTo(Date anotherDate)
          比较两个日期的顺序。
     boolean equals(Object obj)
          比较两个日期的相等性。
3、SimpleDateFormat类把时间字符串和毫秒相互转换。
4、把毫秒转换成中国时间:
   Date date = new Date();(默认当前时间)
   SimpleDateFormat sdf = new SimpleDateFormat("EEEE  yyyy年MM月dd日 HH:mm:ss:SSS");
   System.out.println(sdf.format(date));
5、将字符串转换成Date对象:
    public void f(String s){
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
       Date   date = null;
       date = sdf.parse(s);
       System.out.println(date.getTime());
       System.out.println(date.toString());
   }
6、不记日期格式的方法:
   Date date = new Date();
   DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT);
   System.out.println(df.format(date));
7、Calendar类(抽象类),实现类GregorianCalendar,可任意翻看日历设置时间日期。
8、月份0到11,星期从星期天开始。
9、日历方法:
   abstract  void add(int field, int amount)
          根据日历的规则,为给定的日历字段添加或减去指定的时间量。
10、日历类应用:
   Calendar cal = new GregorianCalendar();
   Date date = new Date();
   cal.setTime(date);
   SimpleDateformat df = DateFormat.getDateInstance(DateFormat.SHORT);
   System.out.println(df.format(cal.getTime());
   cal.add(Calendar.DAY_OF_MONTH,189);
   System.out.println(df.format(cal.getTime());
   cal.add(Calendar.YEAR,-2);
   System.out.println(df.format(cal.getTime());
   cal.set(Calendar.YEAR,2010);
   cal.set(Calendar.MONTH,Calendar.APRIL);
   cal.set(Calendar.DAY_OF_MONTH,1);
   System.out.println(df.format(cal.getTime());
   cal.set(Calendar.DAY_OF_WEEK,Calendar.SUNDAY);
   System.out.println(df.format(cal.getTime());
11、作业:从今天开始算起获取10个18日是星期六。
  public void getSat(){
      Calendar cal = new GregorianCalendar();
      Date date = new Date();
      SimpleDateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
      cal.setTime(date);
      cal.set(Calendar.DAY_OF_WEEK,Calendar.SATURDAY);
      int counter = 0;
      while(counter<=10){
          if(cal.get(Calendar.DAY_OF_MONTH)==18){
              counter++;
             System.out.println(df.format(cal.getTime()));
          }
          cal.add(Calendar.DAY_OF_MONTH,7);
       }
   }
12、作业1:Date与字符串转换。       
    作业2:从今天开始算起找10个润年里面的29是星期五。
    作业3:从键盘输入年和月,然后输出日历。
14、(m%4==0 && m%100!=0 || m % 400==0)闰年。

12月17日 select count(distinct uid) from gold_record a
         where (select count(*)from gold_record where uid=a.uid)>1
 
java流IO流
1、输入流:只能从中读取字节数据,硬盘中的数据流入程序中。
2、输出流:只能向其写入字节数据,程序里面的东西写到硬盘中。
3、按流所处理的数据类型划分为:字符流、字节流。
4、直接和硬盘和键盘、网络打交道的叫节点流(小管子),低级流
5、处理流:封装小管子,封装低级流,StringBuffer,高级流。
6、InputStream和OutputStream用于处理字节数据,输入输出的顶级父类。
7、int read():读取一个字节,返回整型。
   int read(byte[] buffer)
   int read(byte[] buffer,int offset,int length),offset, length是byte[]的 开始和结束的位置。
8、void close():关闭流。
9、读文件在控制台输出的程序:
   FileInputStream(类)低级字节流。
   public static void readInput(String path)
   {
        FileInputStream fis = null;
        fis = new FileInputStream(path);
        int n = 0;
        while((n=fis.read())!=-1){
           System.out.print((char)n);
 }
        fis.close();    

   }
10、byte[]   buffer;
    public static void readInput(String path)
   {
        FileInputStream fis = null;
        byte[] buffer = new byte[512];
        fis = new FileInputStream(path);
        int n = 0;
        whlie((n=fis.read(buffer))!=-1){
            System.out.write(buffer,0,n);
       }
        fis.close();    

   }
11、OutputStream
    void write(int c);
    void write(byte[] buffer);
    void write(byte[] buffer,int offset,int length);
12、public void testOutput(String path){
         FileOutputStream fos = new FileOutputStream(path);
         String s = "面朝大海,春暖花开";
         byte[] buffer = s.getBytes();
         fos.write(buffer,0,buffer.length);
         fos.close();
    }
12、PrintStream
13、字节拷贝
    public void copy(String src,String des){
      FileInputStream fis = new  FileInputStream(str);
      FileOutputStream fos=new FileOutputStream(des);
      byte[] buffer = new byte[512];
      int n = 0;
      while((n=fis.read(buffer))!=-1){
         fos.write(buffer,0,n);
         fos.flush();
      }
      fos.close();
      fis.close();
   }
14、Reader常用方法:字符流BufferedReader
    FileInputStream --FileReader---BufferReader
    public void readerChar(String path){
        try{
           FileReader fr = new FileReader(path);
           BufferedReader br = new BufferedReader(fr);
           String s = null;
           while((s = br.readLine())!=null){
             System.out.println(s);
           }
           br.close();
     }
15、FileWriter:BufferedWriter,PrintWriter.往文件里面写东西
    public void testWrite(String path){
       try{
          FileWriter fw = new FileWriter(path);
          BufferedWriter=new BufferedWriter(fw);
          fw.write("java33 huanying ni ");
          bw.newline();
          bw.close();
          }
    }
16、字符拷贝
   public void testCopy(String src,String des)
   {
      try{
         FileReader fr = new FileReader(src);
         FileWriter fw = new FileWriter(des);
        char[] buffer = new char[512];
        int n=0; 
        while((n=fr.read(buffer))!=-1){
            fr.write(buffer,o,n);
            fw.flush();
        }
        fw.close();
        fw.close();
      }
  }      
17、PrintWriter
18、字节转字符。
  BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
19、作业:拷贝文件夹(与鼠标的拷贝一样的效果)
20、作业:BufferedWriter,PrintWriter的区别。
21、缓冲流:
    BufferedWriter
    BufferedReader 
    BufferInputStream
    BufferOutputStream
    Buffer开辟一块内存空间
22、DataInputstream
    public void testData(String path){
        FileInputStream fis = new FileInputStream(path);
        BufferedInputStream bis = new BufferedInputStream(fis);
        DataInputStream dis = new DataInputStream(bis);
        DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(path)));
        dos.writeUTF("中国武汉");
        dos.writeBoolean(true);
        dos.writeDouble(34.8);
        dos.flush();
        System.out.println(dis.readUTF());
23、字节转字符和字符转字节的编码方式不同时会出现中文乱码。

12月18日

1、序列化  Serializable写对象读对象。
   public class student implements Serializable{
      private int age;
      private String name;
      public Student(){
      }
      public void testObject(String path){
          FileInputStream fis = new FileInputStream(path);
          FileOutputStream fos = new FileOutputStream(path);
          ObjectOutputStream  oos = new ObjectOutputStream(fos);
          ObjectInputStream  ois = new ObjectInputStream(fis);    
          oos.writeObject(new Student(22,"hdj"));
          Student stu = (Student) oos.readObject();
          System.out.println(stu.getAge()+" "+stu.getName());
      }
2、RandomAccessFile
 long getFilePointer()
          返回此文件中的当前偏移量。
 long length()
          返回此文件的长度。
public void testFile(String path) {
  RandomAccessFile raf;
  try {
   raf = new RandomAccessFile(path, "rw");
   raf.writeBoolean(true);
   raf.writeChars("abcdef");
   raf.writeDouble(34.9);
   raf.seek(0);
   boolean flag = raf.readBoolean();
   raf.skipBytes(4);
   char chara = raf.readChar();
   raf.skipBytes(6);
   double value = raf.readDouble();
   System.out.println(flag + "" + chara + "" + value);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
                 }
}      
3、作业1:写一个学生类,存3个学生进去,再读取,先读第二个学生,再读第一个学生,再读第三个学生(使用RandomAccessFile)。        
4、真正做事的是线程。
5、把cpu分成多块多个线程使用。
6、一个进程都有一个主线程main()函数。
7、Thread类,调用start()进入排队等待状态。
8、创进程的方法一:继承thread类,同时覆盖run()方法。
9、
 long getId()
          返回该线程的标识符。
 String getName()
          返回该线程的名称。
 int getPriority()
          返回线程的优先级。
static void sleep(long millis)
          在指定的毫秒数内让当前正在执行的线程休眠(暂停执行)。
static void sleep(long millis, int nanos)
          在指定的毫秒数加指定的纳秒数内让当前正在执行的线程休眠(暂停执行)。
 Thread.State getState()
          返回该线程的状态。
void setName(String name)
          改变线程名称,使之与参数 name 相同。 
10、创进程的方法二:通过实现runnable接口中的run()方法创建一个线程。
11、两种方法创建线程有什么区别:
  n个线程要共享资源就要用第二种方法。
12、作业2:每隔一秒种判断两个文件里面的内容有没有被改变。
13、作业3:用4个线程拷贝myeclipse.exe,拷完可用,4个线程共享一个资源。
14、作业4:练习ObjectInputStream和ObjectOutputStream.       
15、作业5:练习DataInputstream、RandomAccessFile。
16、File:
    long lastModified()
          返回此抽象路径名表示的文件最后一次被修改的时间。
17、作业6:用4个线程拷贝myeclipse.exe:继承thread的方法做,分成4份。

12月19日

1、测试线程是否正处于runnable状态
    isAlive();
2、设置线程的优先级
   tcf.setPriority(Thread.MIN_PRIORITY);
   tcf.start();
   不设置时默认是5(中).
   tcf.getPriority();得到优先级。
3、优先级高的线程不一定先完成任务,1/4个时间片给高优先级线程。
4、join()方法的使用:作业1:写个例子,mian()和子线程。
5、互斥锁:n个线程锁一个对象
   当某个对象用synchronized修饰时,表明该对象在任一时刻只能由一个线程访问。
6、synchronized的使用:作业2:写个例子,4个售票员卖100张票。private int tickets = 100;锁代码。synchronized(this){...}
7、Object类定义了wait(),notify(),notifyAll()方法,不是线程特有的方法,等待和唤醒。
8、作业3:做一个放号器,多个线程同时申请号码不重复,断电后能回复。(两个线程).
9、作业4:两个线程之间如何共享数据。
10、不相关线程、相关但无须同步、同步线程、互斥资源。

网络编程
12月21日
1、计算机网络、操作系统看下。
2、计算机联网可以实现:
   使用远程资源,共享信息、程序和数据,分布处理。
3、中国1995年使用inter网,中部华科,gird网格第三代。
4、星型、总线、环线网络。
5、TCP处于传输层。
6、UDP无连接不可靠的,IP协议位于网络层。
7、A类地址可以组126个网络,0000和1111不能用(0开头一个字节1-126)。
8、B类地址(10开头两个字节128-191)
9、c类地址(110开头三个字节192-223)
10、IP地址是唯一的。
11、TCP有65536个端口(0到65535),ftp端口21,SMTP端口25,HTTP端口80.
12、作业:InetAddress类测试。
13、telnet www.sohu.com 25
14、ps.print("GET /index.html /HTTP1.1");
15、作业:Socket测试。
16、作业:做一个自己规定协议的服务器。
17、BufferedWriter bw = new BufferedWriter(new FileWriter("d:/3.txt",true));
    bw.write(s+"\n");追加。

12月23日

1、ps.println(System.getProperty("line.separator"));换行。
2、作业1:做一个简单的QQ玩以下。
3、三种方法创建类对象。
   1) Student s = new Student();
   2) 反射:Class.forName("com.sunbase.jbsTest.Student").newInstance();
   3) 克隆:Object obj = s.clone();
4、类加载器:Classloader抽象类。
5、Class用来描述对象,就是代表对象的引用。
6、反射:
    三种方式得到class对象
    Student obj = new Student();
    Class c1 = obj. getClass();
    Class c2 = Student.class;
    Class c3 = Class.forName(“package_name.Student”);
    Class c4 = int.class;
    System.out.println(c1.getName() );
    System.out.println(c2.getName() );
    System.out.println(c3.getName() );
    System.out.println(c4.getName() );
7、作业:反射练习。

12月24日

1、用class调用student类中的get方法。
2、Class stu =  Class.forName("com.sunbase.jbsTest.homework12_23.StudentDTO");
Constructor[] cons = stu.getConstructors();
创建对象的方法:Object dto = stu.newInstance() ;
                StudentDTO dt = (StudentDTO) Class.forName("com.sunbase.jbsTest.homework12_23.StudentDTO").newInstance();
2、方法调用:
   Class[] parm1 = new Class[]{String.class,int.class};
   Method set = stu.getMethod("getname",parm1);
   Object res = set.invoke(dto, "hello",5);
   System.out.println(res);
3、两个类对象属性传值:
   BeanUtils.copyProperties(dto,stuF);
   作业:自己写一个copyProperties(dto,stuF)方法,stuF和dto的属性一样。
4、代理模式:
   Logger类的使用:
     
12月25日

1、数据库:Oracle,DB2,SQLServer,MySQL.
2、Class.forName("com.mysql.jdbc.Driver");
   String url = "jdbc:mysql://192.168.33.136:3306/mytest";
   Connection con = DriverManager.getConnection(url, "root", "123");
   PreparedStatement ps = con
 .prepareStatement("select * from publish where user=");
 ResultSet rs = (ResultSet) ps.executeQuery();
 while (rs.next()) {
   System.out.print(rs.getInt(1) + " " + rs.getString(2)+"\t");
   }
 ps.execute();
 con.close();
   Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
   String url = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=sunbase";
   Connection con = DriverManager.getConnection(url, "sa", "123");
  
   加载驱动器load the JDBCDriver
   创建连接:IP、端口号、数据库名、用户名和密码Establish the Database connection
   创建执行语句Create a Statement Object
   执行Execute a Qurey
   结果process the Results
   关闭Close the Connection
3、JDBC API接口
4、导包:工程---new---folder---lib

12月26日

1、腾讯是c/s模式,三个类:awt,swing,swt。
2、数据是用来描述事物的符号记录。
3、selcet b.*,p.* from  book as b, publish p
   where b.publishId=p.publishId;
   select count(pubname) from publish;
   select avg(publishId) from publish;
4、swing:JFrame,JPanle,JScrollPane.
6、作业1:计算器。
7、BorderLayout布局处理器,分为:中央、东、南、西、北。
8、btn.addActionListener(new ActionListener(){});
9、public void actionperformed(ActionEvent e){
       String tmp = ((Button)e.getSource()).getName();
10、作业2:对象传值。      

12月28日
 
1、对象传值:
类:StudentTDO;类:StuFrom;
public static void copyproperities(Object from,Object to){
     Class fs = from.getClass();
     Class fst = to.getClass();
     Field[] fsFrom = fs.getDeclaredFields();
     Field[] fsTo = fst.getDeclaredFields();
     for(int i = 0;i<fsFrom.length;i++){
         String priname = fsFrom[i].getName();
         //判断该属性是否在fsTo中存在
         if(checkExists(priName,fsTo)){
            String name = priName.substring(0,1).toUpperCase()+
            priName.substring(1);
     String getName = "get"+name;
            String steName = "set" +name;
            Method getMethod = fs.getMethod(getName,null);
            Object ret = getMethod.invok(from,null);
     Class retType = getMethod.getRetrunType();
            Method setMethod = fst.setMethod(setName,new Class{retType});
            setMethod.invok(to,ret);
     Method getMethod2 = fst.getMethod(getName,null);
            System.out.println(getMethod2.invok(to,null));
         }
     }  
}
public static boolean checkExists(String priName,Field[] fsTo){
     boolean flag = false;
     for(int i = 0;i<fsTo.length;i++){
         if(priName.equals(fsTO[i].getName()){
              flag = true;
              break;
         }
     }
     return flag;
}
2、复习:
1)构造器不能被继承
2)访问权限。
3)自定义异常。
4)properties类,数据库、程序、系统都有各自的编码方式。

3、写base64编码。
4、outer发送成功没。
5、outlook使用。
6、ehlo要用base64编码,HELO没限制。

1月10日
1、html是解释型语言,速度慢,运行一次解释一次。
2、html结构
<html>
     <head>
           <title>
               标题
           </title>
     </head>
     <body>
          内容
     </body>
</html>
3.bgcolor(背景颜色),text(文本颜色),link,alink,vlik
<hr>,<p></p>,<ol></ol>,<ul></ul>,<li></li>

4.<hr>
  属性:size大小;width宽度;align对齐方式;color.

5.<h>将字体变大
6.<marquee direction=left>我从右向左移
7.<img>通过src设置
8、<front style="front-family:'宋体'; front-size:24px; color:#3300ff">注册页面</front>

1月11日
标准网页(1-5)
1、所有HTML全部小写。
2、为图片添加alt属性。
3.关闭所有标记。
4.给每个属性增加引号。
5.用id属性代替name属性,id必须唯一。
6.Css层叠样式表。
7.内联样式和内部样式以及外部样式。内联:font或<div stytle="backgroundcolor:red"></div>,内部:<stytle></stytle>
外部:<link href="style.css" type="text/css" rel=stylesheet>
8、border 边框,magin框与框之间的距离,padding设置填充,float浮动,img。
9、有标记和无标记的css类选择符:p.Right{}   .center{}
10、标签选择符:body{}
11.id选择符
12.伪类选择符:
a:link{}a:visited{}
a:active{} a:hover{}
13.<link href="style.css" type="text/css" rel=stylesheet>
14.JavaScript脚本语言
与java的区别
是一种可嵌入到WEB当中的基于对象和事件驱动的解释性语言,目的是增强Web客户交互,弥补了HTML的缺陷,前生是LiveScript.
15.基于对象和面向对象、解释和编译解释、强类型和弱类型、静态联编和动态联编。
16、<script language="javascript" type="text/javascript">
var x = 5;
alert(x);
x="我们一起来学习javascript"
alert(x);
document.write(x);
</script>

1月13日
1. String user = request.getParameter("username");
   String pass = request.getParameter("password");
   if((user.equals("cay"))&&(pass.equals("231"))){
       response.sendRedirect("true.jsp");
   }
   esle{
       request.getSession().setAttribute("err","用户密码错误");
       response.sendRedirect("login.jsp");
   }
2. login.jsp:request.getSession().getAttribute("err");
3.<input type="button"  value="添加"  οnclick="javascript:window.location.href='add.jsp'">
4.java代码写在<%   %>中间。
5.Java Server Pages JSP.
6.tomcat把jsp代码解释成java代码。
7.配置tomcat环境变量:tomcat_home
8.web-inf/lib导包。
9.web.xml是所有动态工程的入口。
10.request.setCharacterEncoding("utf-8");(解决编码问题)

1月14日
1.批量删除:
<%
String[] ids = request.getParameterValues("checkbox");
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/mytest";
Connection con = DriverManager.getConnection(url,"root","123");
for(int i=0;i<ids.length;i++){
   PreparedStatement ps = con.prepareStatement("delete from student where StuId=?");
   int id =Integer.parseInt(ids[i]);
   ps.setInt(1,id);
   ps.execute();
}
con.close();
response.sendRedirect("list.jsp");
%>
3.javascript排名第5的语言,事件驱动和页面验证。
4.引号和单引号交替使用。
5.11大内置对象:Globel,String:indexof()如果没有返回-1.
6.var array= new Array(6);array[1].
 sort(),reverse(),
7.Math ,Date.
8.全选和反选:
  checkbox1  onclik="getAll()"
   checkbox2  onclik="unGet()"
 function getAll(){
   var elements = document.form1.checkbox;
   var length=elements.length;
   for(var i=0;i<length;i++){
      var element = elements[i];
      element.checked=true;
   }
}
  function unGet(){
     var elements = document.form1.checkbox;
     var length=elements.length;
for(var i=0;i<length;i++){
      var element = elements[i];
      element.checked=!element.checked;
   }
}
9.下拉列表:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>2jilistbox</title>
</head>
<script language="javascript" type="text/javascript">
function getcity(){
 var indexpro=document.form1.province.value;
 var index=parseInt(indexpro);
 switch(index){
  case 1:
   document.form1.city[0]=new Option("武汉",1);
   document.form1.city[1]=new Option("宜昌",2);
   document.form1.city[2]=new Option("天门",3);
   document.form1.city[3]=new Option("黄岗",4);     
   break;
  case 2:    
   document.form1.city[0]=new Option("长沙",1);
   document.form1.city[1]=new Option("新洲",2);
   document.form1.city[2]=new Option("株洲",3);
   document.form1.city[3]=new Option("韶山",4);
   break;
  
 }
}
</script>
<body>
<form id="form1" name="form1" method="post" action="check.html">
  <label>
  <select name="province" size="1" id="province" οnchange="getcity()">
    <option value="1" >湖北</option>
    <option value="2">湖南</option>
  </select>
  省
  </label>
  <select name="city" id="city">
    </select>
</form>
</body>
</html>

10.、关闭按钮:  οnclick="javascript:window.close()"
     删除按钮:  οnclick="javascript:window.confirm("你确定删除吗?");"
     转向按钮:  οnclick="goPage()"
     跳转页面:  οnclick="javascript:window.location.href='add.jsp'"
11.window.open(url,"","scrollbar=yse,top=100,left=200,width=100,height=100");
12.大的javaw时虚拟机的进程。
13.<input type="checkbox" name="checkbox" value=<%=(rs.getInt(1))%> />

1月15日
1、javascript把所有东西都看成节点:分为3类。
2.元素节点:有始有终的<html></html>
3.属性节点:value="a"
4.文本节点:湖北湖南
5、每个节点都有3个属性:nodeName,nodeType,nodevalue.
6.作业1:添加书项删除项。
7.导JS文件,<script src="com.js"></script>
8.作业2:做树形菜单和框架。
9.作业3:练习document对象。
10.<a href="java33.html" target="MainFrame"">
11.进注册表:regedit 删除 2 3 中的software中的microsoft中的sqlserver

1月17日
1、数据是描述事物的符号记录。
2、关系型数据库设计范式。
3.第一范式:字段值唯一,不可再分。
4.第二范式:数据库表中不存在非关键字段对任一候选关键字段(组合关键字中的任意一个都叫候选关键字段)的部分函数依赖,也即所有非关键字段都完全依赖于任意一组候选关键字。
多对多时把每个多分成一个表,至少3张表。
5.第三范式:不存在传递函数依赖(学生学院表,外键,约束关系),一对多的时候,至少2张表。
6.正序asc,倒序desc.
7.子查询 
select top 2 * from emp_jd
where empId not in(select top 2 empId from emp_jd);

use willPower;
select depId,min(salary),empname
from hr_emp group by depId,salary,empname
having min(salary)>
(select min(salary)
from hr_emp where depId=1)

select * from hr_emp where
salary> any (select min(salary)
from hr_emp group by depId)
8.内连接
select * from hr_emp as e,hr_dep d,hr_job j
where e.depId=d.depId and e.jobId=j.jobId
9.左外连接
select e.*,d.* from hr_emp e left outer join
hr_dep d on e.depId=d.depId;

select  e.*,d.*,j.*
from hr_job j,hr_emp e
left outer join hr_dep d
on e.depId=d.depId where j.jobId=
e.jobId;
10.右外连接

select e.*,d.* from hr_emp e right outer join
hr_dep d on e.depId=d.depId;

11.集合查询(加)
select * from hr_emp where depId<3
union
select * from hr_emp where salary>3000
and depId=4

12.视图

create view emp_jd(empId,empname,depname,jobname)
as select e.empId,e.empname,d.depname,j.jobname from
hr_emp e,hr_dep d,hr_job j where e.depId=d.depId
and e.jobId=j.jobId

13.重命名
sp_rename 'hr_xx','hr_dep','object';

14.增删改字段

alter table student add xueli varchar(50);
alter table student drop column xueli;
alter table student alter column sex varchar(50);

15.建表
create table student (
  stunumber varchar(50) primary key,
  stuname varchar(50) not null,
  sex varchar(50)  not null,
  age int(8)  not null
);
16.删除表
 drop table student;
 
17.创建和删除索引。

create unique index empxu on hr_emp(salary desc);

drop index hr_emp.empxu;

18.增删改
insert into student values('0504111083','胡东杰','男','大四',23);

insert into student(stunumber,stuname,sex,grade,age)
values('0504111084','张文锋','男','大四',23);

delete from student where stunumber='0504111084';

update student set age=20 where stunumber='0504111083';

19.按循序查询
select * from hr_emp
order by salary desc;

select * from hr_emp
order by salary asc;

20.单表查询

select * from hr_emp
order by salary desc;

select * from hr_emp where empname='胡东杰';

select * from hr_emp where salary>4000;

select * from hr_emp where salary between 3000 and 8500;

select * from hr_emp where empname like '胡东_';
 
select * from hr_emp where empname like  '%周%';

select max(salary) from hr_emp ;

select count(depId) from hr_emp;

select * from hr_emp where  depId in (1,2,3);

1月18日
1.finaly{
  if(con!=null)
    con.close();
  }
2.com.microsoft.sqlserver.jdbc.SQLServerDriver
2005以后】

3、连接池
import org.apache.commons.dbcp.BasicDataSource;
public class DataSourceFactory {
 private static BasicDataSource bs;
 public static BasicDataSource getDataSource(){
  if(bs==null){
   bs=new BasicDataSource();
   bs.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
   bs.setUrl("jdbc:microsoft:sqlserver://localhost:1433;DataBaseName=willPower");
   bs.setUsername("sa");
   bs.setPassword("198574520");
   bs.setMaxActive(5);
  }
  return bs;
 } 
}

4.单子模式
public class Shoes {
 private String color;
 private double size;
 private static Shoes shoes;
 public double getSize() {
  return size;
 }
 public void setSize(double size) {
  this.size = size;
 }
 public String getColor() {
  return color;
 }
 public void setColor(String color) {
  this.color = color;
 }
 private Shoes(String color,double size)
 {
  this.color = color;
  this.size = size;
 }
 public static Shoes getInstance(String color){
  if (shoes == null) {
    shoes = new Shoes(color, Math.random() * 10 + 30);
  }
  return shoes;
 }
 public static void main(String[] args){
  Shoes shoes0 = Shoes.getInstance("yellow");
  Shoes shoes1 = Shoes.getInstance("red");
  Shoes shoes2 = Shoes.getInstance("white");
  System.out.println(shoes0.getColor()+"  "+shoes0.getSize());
  System.out.println(shoes1.getColor()+"  "+shoes1.getSize());
  System.out.println(shoes2.getColor()+"  "+shoes2.getSize());
 }
}

5.连接池用法:
con=DataSourceFactory.getDataSource().getConnection();

6.多个类共享Connection con;
通过构造器传con进去,每个DAO都没有权利申请连接。
 
7.把SQL语句定义成常量便于修改。

8.把DAO变成工厂模式但不能用单子模式。
DAOFactory.getBookDAO(con);
DAOFactory.getPublishDAO(con);
DAOFactory.getJobDAO(con);

1月19日

1.事务的特性:
原子性:事务是一个完整的操作。

2.java中的事务:
 Databasename=willPower;selectMothod=cursor启用事务
 con.setAutoCommit(false);
 ps=con.prepareStatement("insert into hr_job values(?)");
 for(int i=0;i<dtos.lenth;i++){
   ps.SetString(1,dtos[i].getName);
   ps.execute();
 }
 con.commit();
 con.setAutocommit(true);
异常里面加:
con.rollback();飞雪连天射白鹿,笑书神侠倚碧鸳。

3.分页
public List findAll(int pageIndex){
   ps = con.prepareStatement("select * from student",ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
   ResultSet rs = ps.executeQuery();
   rs.absolute((pageIndex-1)*3+1);
   rs.previous();
   int counter=0;
   while(rs.next()&&counter<3){
       StuDTO dto = new StuDTO();
       dto.setStuId(rs.getInt(1));
       dto.setStuname(rs.getString(2));
       dto.setStuage(rs.getFloat(3));
       list.add(dto);
       conter++;
   }
}

4、自连接  员工上司表
 selsect m.empname+'working for' as emp,n.empname from tb_employee m,tb_employee n
where n.managerId=n.empId;
  
5.T-SQL语言
局部变量以@开头
DECLARE @变量名 数据类型
赋值
DECLARE @name varchar(50);
SET @name='郭靖';或者
select @name=stuname from student
where stuId='sc002
print @name

6.查找左右同桌
declare @seat int(8)
select @seat=seat from student
where stuname='郭靖'
select * from student where (seat=@seat+1) or (seat=@seat-1)

7.全局变量
以@@开头
8.逻辑控制语句
IF(条件)
begin

end
else begin
end
例子:
declare @avgscore float
select @avgscore=AVG(wrexam) from
tb_stuexam
if(@avgscore>70) begin
print '本班成绩优秀,前两名是'
select top 2* from tb_stuexam order
by wrexam desc end
else begin
print '本班成绩差,后两名是'
select top 2* from tb_stuexam order
by  wrexam asc  end
 
9、while
declare @aint int
select @aint=count(*) from tb_stuexam 
where wrexam<60 print @aint
while(1=1) begin
if(@aint>0)
update tb_stuexam set wrexam=wrexam+2
where wrexam>60
else break
end
select* from tb_stuexam

10.case-end
select sum(price) from tb_product
where month(saletime)=2

select year(saletime),sum(price) as total,sum(case when month
(saletime)=2 then price else 0 end) as '一月份'
,sum(case when month
(saletime)=2 then price else 0 end) as '二月份'
,sum(case when month
(saletime)=4 then price else 0 end) as '四月份'
,sum(case when month
(saletime)=10 then price else 0 end) as '十月份'
from tb_product
group by year(saletime)

11.转账事务
begin transaction
declare @errersum int
set @errersum=0
update hr_bank set money = money+1000
where username ='张三'
set @errersum=@errersum+@@error
update hr_bank set money = money-1000
where username ='李四'
set @errersum=@errersum+@@error
IF @errorSum<>0  --如果有错误
  BEGIN
    print '交易失败,回滚事务'
    ROLLBACK TRANSACTION
  END 
ELSE
  BEGIN
    print '交易成功,提交事务,写入硬盘,永久的保存'
    COMMIT TRANSACTION  
  END
 
12.存储过程(stored Process)

CREATE PROCEDURE getName
@id varchar(50),
@username varchar(50) output
AS
select @username=stuname from student where stuId=@id
GO
调用:
getName 'sc002','sdfs'

13.触发器
是自动调用,在表右键trigger properties创建
CREATE TRIGGER deletebbs  ON [dbo].[bs_area]
FOR DELETE
AS

delete bs_bbs  from  deleted, bs_bbs b where deleted.areaId = b .areaId


14.程序中调用存储过程
Connection con = DriverManager.getConnection(url,"sa","123");
CallableStatement cs=con.prepareCall("{call addBook(?,?,?,?,?)}");
cs.setString(1,"java");
cs.setFloat(2,35);
cs.setString(3,"hudongjie");
cs.setString(4,"33-4443-343");
cs.setInt(5,3);
cs.execute();
cs.close();
con.close();

1月20日(jsp)
jsp内置对象,运行机制
JavaServerPage
1.jsp可以跨平台
2.嵌JS,<script src="al.js"></script>
3.java要嵌入到body中。
4.web(tomcat)把jsp解释成java代码。
5.服务器:Tomcat,Tboss,
6.包放在webcontent/web-inf/lib下,eclipse自动加载。
7.HttpServletRequest,HttpServletResponse
pageContext,config,out,session,page,application
8.发布:把工程放到tomcat的webapp中。
9.tomcat/conf/catalina/localhost/stuDemo.xml,修改发布路径
    <Context  path="/WebContent"  docBase="E:/myjavatest/stuDemo/WebContent" reloadable="true">
    </Context>
10.Servlet是运行在服务器端的java类
11.Sun公司制定Servlet API接口的5个方法
init()初始化
getServletInfo()获取相关信息
service()
destroy()销毁
getServletConfig()获取配置

12.编写servlet程序
 <servlet>
 <servlet-name>HelloWorldServlet</servlet-name>
 <servlet-class>com.sunbase.stuDemo.servlet.HelloWorldServlet</servlet-class>
 </servlet>
 
 <servlet-mapping>
 <servlet-name>HelloWorldServlet</servlet-name>
 <url-pattern>/HelloWorldServlet</url-pattern>//<url-pattern>*.do</url-pattern>
 </servlet-mapping>
13.404错误是找不到路径。
14.作业1:房屋出租,DAO模式,分页,上传下载。
15.作业2:了解servlet。
16.作业3:复习第一阶段,数据库,数据结构。

2月2日
1.SQL的三类
DML(select,insert,update,delete),DDL(create,alter drop),DCL(grant,revoke,setrole)
2.描述项目,注重概念。
3.事务是一种机制,它保证多个SQL语句被当作单个工作单元来处理。
事务是包含一个或多个SQL语句的逻辑工作单元,事务中的SQL语句是能够全部提交,也能全部回滚。
4个特性:ACID准则
4.html中嵌入java代码就是jsp。
5.get请求把参数都显式出来,页面获取的都是string类型的。
6.修改
value="<%=name%>"
request.setCharacterEncoding("utf-8");
String strId=request.getParameterValues("id");
<input type="hidden"  name="id"  value="<%=strId%>">

7.单步按f6
8.servlet
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorldServlet extends HttpServlet {

 protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  // TODO Auto-generated method stub
  PrintWriter out=response.getWriter();
  out.println("<html>");
  out.println("java33");
  out.println("</br>");
  out.println("java33");
  out.println("</html>");
 }

 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  // TODO Auto-generated method stub
  doGet(request,response);
 }
 public static void main(String[] args){
  
 }

}
9.在浏览器中输入地址是doGet()请求。
10.jsp访问servlet,action="abc.do"
   <a href="afa.do">欢迎访问<\a>
11.servlet构造器只能被容器调用一次,单子模式
12.<servlet>
 <servlet-name>HelloWorldServlet</servlet-name>
 <servlet-class>com.sunbase.stuDemo.servlet.HelloWorldServlet</servlet-class>
        <load-on-startup>1 </load-on-startup>
        <init-param>
          <param-name>config</param-name>
          <param-value>/WEB-INF/config.xml</param-value>
        </init-param>
  </servlet>
13.构造器比初始化方法先调用,一个构造器被调用紧接着调用初始化方法,再调用别的构造方法。
14.init()方法
<servlet>
<init-param>
  <param-name>driverClassName</param-name>
  <param-value>com.microsoft.jdbc.sqlserver.SQLServerDriver</param-value>
</init-param>
<init-param>
  <param-name>username</param-name>
  <param-value>hudongjie</param-value>
</init-param>
</sevlet>
public void init() throws ServletException {
    String driver=this.getInitParameter("driverClassName"); 
    String username=this.getInitParameter("username"); 
}  

protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  // TODO Auto-generated method stub
               
  PrintWriter out=response.getWriter();
  out.println("<html>");
  out.println(driver);
  out.println("</br>");
  out.println(username);
  out.println("</html>");
 }
15.获取当前工程的绝对路径
  String path = this.getServletContext().getRealPath("/");
16.HTTPServlet把service换成了doGet(),doPost(),doPut().
17.jsp也是单子模式,第一次启动时servlet比jsp快,以后速度一样。
18.regedit进注册表
19.servlet是运行在服务器端的java类,处在容器里面的单子模式。
20.顶级接口:Servlet,ServletConfig
   抽象类:GeneralServlet
   HttpServlet
21.servlet里面只能定义公共变量或常量。只能写无参构造器,因为反射机制只能调用无参构造器。
22.servlet的生命流程
1)web服务器启动时自动装载web.xml文件
2)如果servlet有load-on-startup就创建servlet实例并调用init方法(反射单子模式创建)
3)如果没有load-on-startup web容器就在客户端第一次访问到达的时候创建servlet实例并调用init方法
4)Servlet进驻内存
5)Servlet调用doGet或dopost方法
6)容器关闭时自动销毁Servlet实例

23.Connection con = DataSourceFactory.getDataSource();
   BookDAO dao=DAOFactory.getBookDAO(con);
   List<BookDTO> books=dao.findAll();
   request.setAttribute("BOOK",books);
   requestDispatcher rd = request.getRequestDispatcher("bookList.jsp");
   rd.forward(request,response);
   在jsp里面获取:
   java.util.List<BookDTO> list = (java.util.List) request.getAttribute("BOOK");

2月3日
1.加/表示到webcontent中去找,绝对路径。
2.复习servlet的生命流程
3.mvc概念
4.servlet动态添加出版社
  <td><select name=" "
  <%
  List<PublishDTO> pubs=(List)request.getAttribute("pubs");
  for(int i=0;i<pubs.size();i++){
     PublishDTO dto = pubs.get(i);
     %>
     <option value="<%=dto.getPublishId() %>"><%=dto.getPubname()%></option>
     <%
    }
     %>
5.M是模型是javabean:DAO,DTO,V是视图用jsp,C是控制器用servlet做。
6.session只要服务器没关就有用作用范围是一个会话,默认的是30分钟,request.getSession.setAttribute();
与response.sendRedirect();联合使用
response.sendRedirect()是2次转向

2月4日
1.mvc,程序不能耦合太紧,dao,dto数据模型连接数据库获取数据,模型不一定要用dao,dto,还可以用EJB,视图jsp,control控制
servlet做的事情是:
    1)获取数据或存储数据调用模型DAO,
    2)servlet与servlet,jsp共享数据用request、session,
    3)转向:servlet只运行在服务器上,servlet转向servlet都是同一个request,response。
2.CRUD,不允许jsp调用模型
3.分页:
public List findAll(int pageIndex){
   ps = con.prepareStatement("select * from student",ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
   ResultSet rs = ps.executeQuery();
   rs.absolute((pageIndex-1)*3+1);
   rs.previous();
   int counter=0;
   while(rs.next()&&counter<3){
       StuDTO dto = new StuDTO();
       dto.setStuId(rs.getInt(1));
       dto.setStuname(rs.getString(2));
       dto.setStuage(rs.getFloat(3));
       list.add(dto);
       conter++;
   }
}

booklistAction中的代码:

String page = request.getParameter("curpage");
int curpage = 1;
if(page!=null) curpage=Integer.parseInt(page);
Connection con = DataSourceFactory.getDataSource().getConnection();
BookDAO dao = DAOFactory.getBookDAO(con);
int totalpage = dao.getTotalPage();
if(curpage>totalpage) curpage=totalpage;
if(curpage<1) curpage= 1;
List<BookDTO> books = dao.getAll(curpage);
con.close();
request.setAttribute("BOOK",books);
PageDTO urlPage=new PageDTO();
urlPage.setCurpage(curpage);
urlPage.setTotalpage(totalpage);
request.setAttribute("urlPage",urlPage);

PageDTO代码:
public class PageDTO {
   private int curpage;
   private int totalpage;
public int getCurpage() {
 return curpage;
}
public void setCurpage(int curpage) {
 this.curpage = curpage;
}
public int getTotalpage() {
 return totalpage;
}
public void setTotalpage(int totalpage) {
 this.totalpage = totalpage;
}
}
4.获取最大页:
public int getTotalPage(int count){
  int page=1;
  ps = con.prepareStatement("select count(*) from book");
  rs = ps.executeQuery();
  if(rs.next()){
     page = (rs.getInt(1)+count-1)/count;
  }
  return page;
}
5.int curpage=1;
String curpageStr = request.getParameter("curpage");
if(curpageStr==null) curpage=1;
curpage=Integer.parseInt(curpageStr);
if(curpage>dao.getTotalPage())   curpage=1;
6.setAttribute()装的是对象。new Integer(curpage).toString().
7.文件上传下载:
下载:FileInputStream,response.getWriter()
上传:request.getInputStream,FileOutputStream

下载:
  String path = this.getServletContext().getRealPath("/");
  String realPath = path+"WEB-INF/upload/002.pdf";
  System.out.printStream(realPath);
  File file = new File(realPath);
  OutputStream out = response.getOutputStream();
  response.setContentType("application/pdf");
  response.setContentLength((int)file.length());
  response.addHeader("Content-Disposition","attachment;filename="+file.getName());
  InputStream is = new FileInputStream(file);
  byte[] buffer = new byte[512];
  int n = 0;
  while((n=is.read(buffer))!=-1){
    out.write(buffer,0,n);
  }
  is.close();

上传:
 改成2进制提交 form表单属性  enctype="multipart/form-data"
  DiskFileUpload dfu = new DiskFileUpload();
  dfu.setSizeMax(4*1024*1024);
  dfu.setSizeThreshold(4096);
  dfu.setRepositoryPath("E:\\temp");
  List filem = dfu.parseRequest(request);
  Iterator its = filem.iterator();
  while(its.hasNext()){
      FileItem item = (FileItem) its.next();
      if(!item.isFormField()){
          InputStream is = item.getIntputStream();
          String name = item.getName();
          long size = item.getSize();
          String fileName=name.substring(name.lastIndexOf("\\")+1);
          FileOutputStream fos = new FileOutputStream("E:/temp/"+fileName,true);
          byte[] buffer = new byte[512];
          int n=0;
          while((n=is.read(buffer))!=-1){
              fos.write(buffer,0,n);
          }
          fos.close();
      }
  }   
 
8.问号传多个参数:
  href="update.jsp?id=<%=rs.getString(1)%>&name=<%=rs.getString(2)%>&class=<%=rs.getString(4)%>"

2月5日
标签
1.分类:
 Core tags,Database Access tags,Format tags.
2.使用标签
第一种方式:<%@ taglib uri="WEB_INF/c.tld" prefix="c" @%>导入c.tld
第二种方式:<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" @%>
            <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
3.一般用途标签:<c:out value="${dto.bookname}"/>输出,或者直接写${dto.bookname}
4.获取属性<c:set var="dto" value="${book}"/>
默认调用request.getAttribute("book");
<input name="bookname" type="text" value="${dto.bookname}"/>
或者不写c:set,<input name="bookname" type="text" value="${book.bookname}"/>
5.从小到大:page,request,session,Application
6.迭代标记 items 是集合
<c:forEach var="dto" items="${book}">
<tr>
<td>${dto.bookid}</td>
<td>${dto.bookname}</td>
<td>${dto.price}</td>
<td>${dto.author}</td>
<td>${dto.isbn}</td>
<td>${dto.publishId}</td>
</tr>
</c:forEach>
7.判断标记
<c:if test="${dto.bookId>5}">


</c:if>
8.<c:choose>
     <c:when test="">
     </c:when>
     <c:when test="">
     </c:when>
     <c:otherwise >
     </c:otherwise>
  </c:choose>
9.编码转换
  String name=new String(request.getParameter("names").getBytes("ISO-8859-1"),"UTF-8");
10.xml主要用于显式数据和存贮传输数据。
11.三种xml
1)格式良好的,没有dtd验证
2)格式良好的,有dtd验证 
3)自定义的xml
12.有始有尾区分大小写,有且仅有一个根节点。
<a href="">胡东杰</a>叫元素节点,a叫标记,href叫属性节点
“胡东杰”叫文本节点
13.#PCDATA文本类型
14.xml范例:
<?xml version="1.0" encoding="UTF-8"?>
<datasources>
  <datasource key="A">
     <driverClassName>com.mysql.jdbc.Driver</driverClassName>
     <url>jdbc:mysql://localhost:3306/myTest</url>
     <username>root</username>
     <password>123</password>
  </datasource>
  <datasource key="B">
     <driverClassName>com.mysql.jdbc.Driver</driverClassName>
     <url>jdbc:mysql://localhost:3306/myTest</url>
     <username>root</username>
     <password>123</password>
  </datasource>
</datasources>
15.两种解析xml的 方式,可扩展标记语言
 DOM,SAX
16.SAX解析方式:
 碰到哪个节点调用哪个方法,方法是自己写的,适合于大型文件解析,不占用内存,要人做的事情太多。
17.DOM解析方式:
 把整个XML文件加载到内存文件中,马上生成一颗树,可以在边解析的时候边修改枝叶,比较灵活,
 便于修改,耗内存,适合小型文件解析
18.DOM解析(sun实现的)范例
 DocunemtBuilder 创建
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
       try {
       DocumentBuilder builder = factory.newDocumentBuilder();
       Document doc = builder.parse("hello.xml");
       Element root = doc.getDocumentElement();
       System.out.println(root.getNodeName() + " " + root.getNodeValue()
  + " " + root.getNodeType());
       Node node = root.getFirstChild();
       System.out.println(node.getNodeName() + " " + node.getNodeValue()
  + " " + node.getNodeType());
    }

19.
1)把两个jar文件放到lib里面去
2)把头部信息写进来
3)
20.DOM解析xml获取JDBC信息
        DocumentBuilder builder = factory.newDocumentBuilder();
 Document doc = builder.parse(path);
 Element root = doc.getDocumentElement();
 Node child = root.getFirstChild();
 while(child!=null){
  if(child.getNodeType()==Node.ELEMENT_NODE){
   String name = child.getNodeName();
   Node subChild = child.getFirstChild();
   String value="";
   if(subChild!=null){
        value = subChild.getNodeValue();
   }
   pintValue(name,value);
  }
  child = child.getNextSibling();
 }
 System.out.println(ds.getDriver());
 System.out.println(ds.getUrl());
 System.out.println(ds.getUsername());
 System.out.println(ds.getPassword());
 System.out.println(ds.getMaxActive());
文本节点的名字是#text
21.解析xml并调用方法范例
傻瓜解析器:digester是把dom合sax组合封装
public class MVCConfig {
 private static MVCConfig config;
 private static Map<String, ActionDTO> map = new HashMap<String, ActionDTO>();
 private static DataSourceDTO dto = new DataSourceDTO();

 public static Map<String, ActionDTO> getMap() {
  return map;
 }

 public static DataSourceDTO getDto() {
  return dto;
 }

 public static MVCConfig getConfig(String path) {
  if (config == null) {
   config = new MVCConfig(path);
  }
  return config;
 }

 private MVCConfig(String path) {
  Digester dig = new Digester();
  dig.push(this);
  dig.addCallMethod("mvc-config/datasource", "addDataSource", 5);
  dig.addCallParam("mvc-config/datasource/driver", 0);
  dig.addCallParam("mvc-config/datasource/url", 1);
  dig.addCallParam("mvc-config/datasource/username", 2);
  dig.addCallParam("mvc-config/datasource/password", 3);
  dig.addCallParam("mvc-config/datasource/maxActive", 4);
  dig.addCallMethod("mvc-config/action-mappings/action", "addAction", 3);
  dig.addCallParam("mvc-config/action-mappings/action", 0, "path");
  dig.addCallParam("mvc-config/action-mappings/action", 1, "name");
  dig.addCallParam("mvc-config/action-mappings/action", 2, "redirect");
  try {
   dig.parse(path);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (SAXException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 public void addDataSource(String driver, String url, String username,
   String password, String maxActive) {
  dto.setDriver(driver);
  dto.setUrl(url);
  dto.setPassword(password);
  dto.setUsername(username);
  dto.setMaxActive(Integer.parseInt(maxActive));
 }
 public void addAction(String path,String name,String redirect){
  ActionDTO action = new ActionDTO();
  action.setPath(path);
  action.setName(name);
  action.setRedirect(redirect);
  map.put(path, action);
 }

}

所有参数类型都是String类型。

2月6日
1.MVC,control是调用模型,做业务逻辑和跳转。
2.建一个总的ActionServlet,路径改成*.do
  页面跳转到servlet时路径改成add.do,del.do,updata.do,preadd.do
  删除其他servlet里面的doGet,doPost方法,不再是servlet
3.ActionServlet的写法
  URL是全部路径,URI是部分路径
  String uriPath = request.getRequestURI();
  int start = uriPath.lastIndexOf("/");
  int end = uriPath.lastIndexOf(".");
  String path = uriPath.subString(start+1,end);
  if(path.equals("bookList")){
      BookListServlet bookList = new BookListServlet();
      BookList.process(request,response);
  }
4. String realpath = this.getServletContext().getRealPath("/");
5.<init-param>
     <param-name>config</param-name>
     <param-value>/WEB-INF/config.xml</param-value>
  </init-param>

6.
1)精简web.xml文件,创建总的servlet(ActionServlet),修改servlet路径
2)如何将路径名和类名连接起来,想到用xml文件存储
3)将解析xml放到init方法中去,将解析使用单子模式
4)通过反射机制创建类和调用方法
  建一个抽象类Action,包含proccess抽象方法,让所有Action继承这个抽象类,实现proccess方法
  String className=dto.getName();
  Action obj = (Action)Class.froName(className).newInstance();
  obj.proccess(request,response);

2月9日
1.response.sendredirect,重定向,服务端返回要求客户端重新输入请求,将丢失request数据。
2.content-param,init-param,load-on-sartup,servlet-name,servlet-class
3.所有数据封装在request中。
4.Filter过滤器,作用:修改编码方法,验证,获取权限。
5.Filter接口有三个方法init(),doFilter(),distroy().
6.<filter>
 <filter-name>SetCharacterEncodingFilter</filter-name>
 <filter-class>
  com.willPower.servlet.SetCharacterEncodingFilter
 </filter-class>
 <init-param>
  <param-name>encoding</param-name>
  <param-value>UTF-8</param-value>
 </init-param>
</filter>
<filter-mapping>
 <filter-name>SetCharacterEncodingFilter</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>
public class SetCharacterEncodingFilter implements Filter {

 protected String encoding = null;
 protected FilterConfig filterConfig = null;

 public void destroy() {
  this.encoding = null;
  this.filterConfig = null;
 }

 public void doFilter(ServletRequest request, ServletResponse response,
   FilterChain chain) throws IOException, ServletException {
  request.setCharacterEncoding(encoding);
  chain.doFilter(request, response);
 }

 public void init(FilterConfig filterConfig) throws ServletException {
  this.filterConfig = filterConfig;
  this.encoding = filterConfig.getInitParameter("encoding");
 }
}
7.监听器配置
 <listener>
    <listener-class>com.willpower.testServlet.hudongjie.SessionListener</listener-class>
 </listener>
public class SessionListener implements HttpSessionListener {
    public static int sessionCount;
 public void sessionCreated(HttpSessionEvent arg0) {
  sessionCount++;
 }
 public void sessionDestroyed(HttpSessionEvent arg0) {
  sessionCount--;
 }
}
8.zh-cn中文,en-us英语,i18n技术
 ResourceBundle
 1)中文建临时文件,写之前修改编码方式
 建tempapplication.properties文件,内容:
 bookname=书名
 author=作者
 2)建application_zh_CN.properties文件,空的
 3)建temp.bat文件,内容:
 native2ascii.exe -encoding utf-8 tempapplication.properties application_zh_CN.properties
 4)双击temp.bat文件,如果application_zh_CN.properties文件里面有值表示成功。
 文件都建在SRC根目录下面
9.导入ResourceBundle
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<fmt:setBundle basename="application"/>
<td><fmt:message key="bookname"></fmt:message></td>
10.dom4j写xml文件
   public void writerXML(String path){
 Document doc = DocumentHelper.createDocument();
 Element root = doc.addElement("package");
 Element action=root.addElement("action");
 action.addAttribute("name","login");
 action.addAttribute("class", "com.willPower.loginAction");
 Element result1 = action.addElement("result");
 result1.setText("/login.jsp");
 Element action1=root.addElement("action");
 action1.addAttribute("name","list");
 action1.addAttribute("class", "com.willPower.listAction");
 Element result2 = action1.addElement("result");
 result2.setText("/list.jsp");
 OutputFormat format = OutputFormat.createPrettyPrint();
 XMLWriter out = new XMLWriter(new FileOutputStream(path),format);
 out.write(doc);
 out.close();
   }
   public static void main(String[] args) {
  Dom4jTest test = new Dom4jTest();
  test.writerXML("strust2.xml");
 }
11.dom4j解析xml文件
  "/package/action/@name"
 public void readXML(String path){
  SAXReader reader = new SAXReader();
  try {
   Document doc=reader.read(path);
   Element root = doc.getRootElement();
   Iterator its = root.elementIterator();
   String name=null;
   while(its.hasNext()){
    Element element = (Element)its.next();
    Action2DTO dto = new Action2DTO();
    dto.setName(element.attributeValue("name"));
    dto.setClassname(element.attributeValue("class"));
    for(Iterator it=element.elementIterator();it.hasNext();){
     Element result=(Element)it.next();
     name = result.attribute("name").getValue();
     String forward = result.getText();
     dto.getMap().put(name, forward);
    }
    System.out.println(dto.getName()+"  "+
      dto.getClassname()+"  "+
      dto.getMap().get(name));
   }
  } catch (DocumentException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
 }
 public void readXML(String path){
  SAXReader reader = new SAXReader();
  try {
   Document doc=reader.read(path);
   Element root = doc.getRootElement();
   List<Element> list=root.elements("action");
   for(int i=0;i<list.size();i++){
    Element element = list.get(i);
    Element result=element.element("result");
    Action2DTO dto = new Action2DTO();
    dto.setName(element.attributeValue("name"));
    dto.setClassname(element.attributeValue("class"));
    String name = result.attribute("name").getValue();
     String forward = result.getText();
     dto.getMap().put(name, forward);
    System.out.println(dto.getName()+"  "+
      dto.getClassname()+"  "+
      dto.getMap().get(name));
   }
  } catch (DocumentException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
public class Dom4jGetConfig {
 private static Dom4jGetConfig config;
 private static Map<String, ActionDTO> map = new HashMap();
 private static DataSourceDTO dto = new DataSourceDTO();

 public static Map<String, ActionDTO> getMap() {
  return map;
 }

 public static DataSourceDTO getDto() {
  return dto;
 }

 public static Dom4jGetConfig getConfig(String path) {
  if (config == null) {
   config = new Dom4jGetConfig(path);
  }
  return config;
 }

 private Dom4jGetConfig(String path) {
  SAXReader reader = new SAXReader();
  try {
   Document doc = reader.read(path);
   Element root = doc.getRootElement();
   Element element = (Element) root.element("datasource");
   List<String> list = new ArrayList();
   for (Iterator it = element.elementIterator(); it.hasNext();) {
    Element result = (Element) it.next();
    list.add(result.getText());
   }
   dto.setDriver(list.get(0));
   dto.setUrl(list.get(1));
   dto.setUsername(list.get(2));
   dto.setPassword(list.get(3));
   dto.setMaxActive(Integer.parseInt(list.get(4)));
   Element element1 = (Element) root.element("action-mappings");
   for(Iterator it=element1.elementIterator();it.hasNext();){
    Element result=(Element)it.next();
    String name = result.attribute("name").getValue();
    String path1 = result.attributeValue("path");
    String redirect = result.attributeValue("redirect");
    ActionDTO action = new ActionDTO();
    action.setPath(path1);
    action.setName(name);
    action.setRedirect(redirect);
    map.put(path1, action);
   }

  } catch (DocumentException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}
2月10日
1.excel数据到sql,sql数据到excel
2.Ajax
Asynchronous Javascript and XML
异步提交同步处理
3.注册时同步判断用户名是否已存在
4.Ajax以xml方式返回时解析xml
<script language="javascript" type="text/javascript">
var xmlHttp;
function createXMLHttp(){
 if(window.ActiveXObject){
   xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  else{
   xmlHttp = new XMLHttpRequest();
  }
}
function check(){
  createXMLHttp();
  var username = document.form1.username.value;
  var url="validate?username="+username;
  xmlHttp.open("GET",url,true);
  xmlHttp.send(null);
  xmlHttp.onreadystatechange=callback;
}
function callback(){
  if(xmlHttp.readyState==4){
     if(xmlHttp.status==200){
  parseMessage();
  }
  }
}
function parseMessage(){
 var message = xmlHttp.responseText;
 var result = document.getElementById(  "result");
 result.innerHTML="<font color=\'red\'>"+message+"</font>";
}
</script>

2月11日
1.CVS版本控制器,卸载时要到注册表中删除。
2.strusts框架,将request对象赋给form对象。
Class dto = StudentDTO.class;
Method getMethod=dto.getMethod("getWeight",null);
Object getMethod.invoke(dto.newInstance(),null);

3.Enumeration parameters = request.getParameterNames();
  Class dto= ActionDTO.getClass();
  Field[] fields = dto.getDeclaredFields();
  for(Field fls:fields){
     fls.getType();
     fls.getName();
  }
  while(parameters.hasMoreElements.(){
     String name = (String)parameters.nextElement();
     if(checkfield()){
         String value = request.getParameter(name);
         String setMethodName = "set"+name.substring(0,1).toUppercase()+name.subString(1);
         Field filedName;
         filedName=dto.getDeclaredField(name);
         Method method = dto.getMethod(setMethodName,filedName);
         method.invoke(
        
  }
  }

4.跳转写一个xml文件配置路径
  如name="123" path="login"
    name="456" path="list"
5.hibernate学习
  持久化工具,固化
  ORM
  JDO(SUN公司)
  ibadis
6.pojo持久化对象
1)建hibernate.cfg.xml
2)持久化对象(DTO)
3)xml将表和对象映射


select e.*,d.* from book e left outer join publish d on e.publishId=d.publishId;


7.js做判断
<script language="javascript" type="text/javascript">
function check(){
    var name = document.form1.name.value;
 var age = document.form1.age.value;
 var email = document.form1.email.value;
 if(name==""||name.length<4||name.length>20){
    alert("名字不合规范!");
    return false;
 }
 if(age==""){
  alert("年龄不能为空!");
    return false;
 }
 if(isNaN(age)){
  alert("年龄必须为数字!");
    return false;
 }
 if(email=="")
 {
    alert("邮箱名不能为空!");
    return false;
 }
 if(email.indexOf("@",0)==-1){
      alert("邮箱名格式不正确!");
    return false;
 }
 
}
</script>
</head>

<body>
<form id="form1" name="form1" method="post" action="object.html" οnsubmit="return check()">
  <table width="49%" border="1" cellspacing="1" cellpadding="1">
    <tr>
      <td width="39%"> 姓名:</td>
      <td width="61%"><input name="name" type="text" id="name" /></td>
    </tr>
    <tr>
      <td>年龄:</td>
      <td><input name="age" type="text" id="age" /></td>
    </tr>
    <tr>
      <td>邮件地址:</td>
      <td><input name="email" type="text" id="email" /></td>
    </tr>
    <tr>
      <td>个人说明:</td>
      <td><input type="text" name="textfield" /></td>
    </tr>
    <tr>
      <td><input type="submit" name="Submit" value="提交" /></td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
  </table>
</form>
</body>
</html>

9.全选反选删除
function getAll(){
     var elements = document.getElementsByName("checkbox");
     var a = document.getElementById("checkbox1");
    var length = elements.length;
    for(var i=0;i<length;i++){
    if(a.checked==true) elements[i].checked=true;
    if(a.checked==false) elements[i].checked=false;
    }
   }
  function unGet(){
     var elements = document.getElementsByName("checkbox");
      var a = document.getElementById("checkbox2");
  var leng=elements.length;
  for(var i=0;i<leng;i++){
     var element = elements[i];
  if(a.checked==true) element.checked=!element.checked;
  }
  }
  function check(){
      if(!window.confirm("你确认删除吗?")){
       return false;
   }
  }

10.过滤器做权限
public class userFilter implements Filter
{
    public void destroy()
    {
 
    }
    public void doFilter( ServletRequest request,
        ServletResponse response,
        FilterChain chain) throws IOException, ServletException
    {
 HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;     
    HttpSession session = req.getSession(true);
    String uripath=req.getRequestURI();
    int start=uripath.lastIndexOf("/");
 int end=uripath.lastIndexOf(".");
 String path=uripath.substring(start+1,end);
 UserinforDTO udt = (UserinforDTO) session.getAttribute("userinfor");
 //判断如果没有取到用户信息,就跳转到登陆页面
    if (udt == null&&!path.equalsIgnoreCase("login"))
    {
     //跳转到登陆页面  
      res.sendRedirect(req.getContextPath()+"/User/login.jsp");
    }
    else
    {
         //已经登陆,继续此次请求
         chain.doFilter(request,response);
    }   
    }
   public void init(FilterConfig filterConfig) throws ServletException
   {
   }
}

 

  <filter>
  <filter-name>userFilter</filter-name>
  <filter-class>com.servlet.userFilter</filter-class>
  </filter>

  // <servlet>
  //<description>This is the description of my J2EE component</description>
  //<display-name>This is the display name of my J2EE component</display-name>
  //<servlet-name>userFilter</servlet-name>
  //<servlet-class>com.servlet.userFilter</servlet-class>
  //</servlet>

  <filter-mapping>
  <filter-name>userFilter</filter-name>
  <url-pattern>*.do</url-pattern>
  </filter-mapping>
  <filter-mapping>
  <filter-name>userFilter</filter-name>
  <url-pattern>*.jsp</url-pattern>
  </filter-mapping>

3月5日
Srtuts
1.jsp modle1
(浏览器)--(jsp-javabean)--(DB)
 jsp model 2
(浏览器)--(servlet--jsp--javabean)--(db)
jsp页面的java代码基本没有了

2.MVC设计模式
M模型:JAVABEAN
V视图:JSP等
C控制器:SERVLET

3.STRUTS
优点:
(1)struts标签 taglib
(2)页面导航
Struts是源代码开放的企业级Web应用开发框架,它的设计目的是从整体上减轻构造企业Web应用的负担。

4.使用struts开发的4个步骤:
(1)给项目添加struts支持--.jar,tld,dtd
    
5.action form
6.struts框架登录的例子
 (1)LoginForm.java文件
 public class LoginForm extends ActionForm {

 private static final long serialVersionUID = 1L;
 private String userName;
 private String password;
 public String getUserName() {
  return userName;
 }
 public void setUserName(String userName) {
  this.userName = userName;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 
}

 (2)CheckLoginBean.java文件
  public class CheckLoginBean {
 public boolean CheckUserName(String userName){
  boolean result =false;
  try{
   if("softeem".equals(userName)){
    result = true;
   }
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   
  }
  return result;
 }
  }

 (3)LoginAction.java文件
 public class LoginAction extends Action {

 public ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  String forward = "lost";
  try{
   LoginForm lForm = (LoginForm)form;
   CheckLoginBean clBean = new CheckLoginBean();
   if(clBean.CheckUserName(lForm.getUserName())){
    forward = "success";
   }
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   
  }
  return mapping.findForward(forward);
 }
 
 }

 (4)struts-config.xml文件的配置
 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
<data-sources>
  
  <data-source type="org.apache.commons.dbcp.BasicDataSource">
   <set-property property="autoCommit" value="false" />
   <set-property property="description"
    value="SQLServer Data Source" />
   <set-property property="driverClassName"
    value="com.microsoft.jdbc.sqlserver.SQLServerDriver" />
   <set-property property="url"
   value="jdbc:microsoft:sqlserver://localhost:1433;DataBaseName=willPower;selectMothod=cursor" />
   <set-property property="username" value="sa" />
   <set-property property="password" value="198574520" />
   <set-property property="maxCount" value="10" />
   <set-property property="minCount" value="2" />
  </data-source>
</data-sources>
 <form-beans>
 <form-bean name="loginForm" type="com.softeem.struts.LoginForm"/>
 </form-beans>
 <action-mappings>
  <action path="/login" input="/page/login.jsp"
    name="loginForm" type="com.softeem.struts.LoginAction"
    scope="request">
    <forward name="lost" path="/page/lost.jsp"/>
    <forward name="success" path="/page/success.jsp"/>
  </action>
 </action-mappings>
</struts-config>

 (5)web.xml文件的配置
 <?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
  <servlet-name>action</servlet-name>
  <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
  <init-param>
   <param-name>config</param-name>
   <param-value>/WEB-INF/struts-config.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  <servlet-name>action</servlet-name>
  <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

 (6)login.jsp页面代码
 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head> 
    <title>用户登录</title>
  </head>
 
  <body>
    <html:form action="login.do" focus="userName">
    用户名:<html:text property="userName"></html:text>
    <br>
    密  码:<html:password property="password"></html:password>
    <br>
    <html:submit>提交</html:submit>
    <html:reset>重置</html:reset>
    </html:form>
  </body>
</html> 

3月6日
1.验证
 (1)在src根目录下建一个Application.properties文件
  配3个属性
  errors.header=<span style="color:red;">
  errors.footer=</span>
  或者errors.header=<script>alert("
      errors.footer=")</script>
  errors.required=用户名密码不能为空!
 (2)在Struts-config中配置
 <message-resources parameter="Application"></message-resources>
 在login的action中加一个属性validate="true"
 (3)在login.jsp中加一个<html:errors property="password"/><br>
 (4)在LoginForm中重写validate方法
        public ActionErrors validate(ActionMapping mapping,
   HttpServletRequest request) {
  ActionErrors errors = new ActionErrors();
  if("".equals(this.getUserName())||"".equals(this.getPassword())){
     errors.add("password", new ActionMessage("errors.required"));
  }
  return errors;
 }

3月9日
1.在LoginForm.java中重写reset()方法,给userName="username"和password="123"赋初始值。
ShowLoginACtion 中写:
LoginForm lform = (LoginForm )form;
request.setAttribute("Logform",lform);

showLogin.jsp中写:
<html:text name="Loginform" property="userName"></html:text><br>
<html:text name="Loginform" property="password"></html:text><br>

struts-config中配置action

2.DispatchAction
struts-config.xml 中 parameter="operator
使用DispatchAction 做计算器
(1)创建CalaForm extends ActionForm,属性int num1,int num2,float result;
(2)创建CalaAction 继承DispatchAction ,在CalaAction 中写public ActionForward toAdd(ActionMapping mapping,....)方法
String forward="result";
CalaForm cForm = (CalaForm)form;
int num1=cForm.getNum1();
int num2=cForm.getNum2();
int result=num1+num2;
cForm.setResult(result);
request.setAttribute("oper","加");
return mapping.findForward(forward);
(3)建两个jsp页面,计算页面和显示结果页面
caloper.jsp
<script type="text/javascript">
function toOper(key){
    sdocument.forms[0].operate.value=key;
    document.forms[0].submit();
}
</script>
第一个数:<html:text property="num1"></html:text>
第二个数:<html:text property="num2"></html:text>
<<input type="button" value="加" οnclick="toOper('toAdd')"/>
<input type="button" value="减" οnclick="toOper('toMinus')"/>
<input type="button" value="乘" οnclick="toOper('toMultiply')"/>
<input type="button" value="除" οnclick="toOper('toDivide')"/>
<input type="hidden" name="operate"/>

(4)配置action和form-beans
 <action path="/cala" name="calaForm"
    type="com.sunbase.teststruts.login.CalaAction"
    scope="request" attribute="cForm" parameter="operate">
     <forward name="result" path="/page/calresult.jsp"></forward>
    </action>
(5)写calresult.jsp 直接写在body中导入
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
 第一个数:<bean:write name="cForm" property="num1"/><br
 第二个数:<bean:write  name="cForm" property="num2"/>
 计算方式:<bean:write  name="oper" /><br>
 计算结果:<bean:write  name="cForm" property="result"/>
(6)要配置这个:<message-resources parameter="Application"></message-resources>
3.验证
ApplicationResources.properties编码要改成UTF-8
native2ascii -encoding utf-8 ApplicationResources.properties ApplicationResources2.properties

(1)将num1.num2改成String类型

(2)在action中加 input="/page/caloper.jsp"

(3)在calaAction中写以下代码:
public ActionForward toAdd(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  String forward="result";
  CalaForm cForm = (CalaForm)form;
  if(!"".equals(cForm.getNum1())&&!"".equals(cForm.getNum2())){
   int num1=Integer.parseInt(cForm.getNum1());
   int num2=Integer.parseInt(cForm.getNum2());
   int result=num1+num2;
   cForm.setResult(result);
   return mapping.findForward(forward);
  }else{
   ActionMessages errors =check(cForm);
   if(!errors.isEmpty()){
       super.saveErrors(request,errors);
     return mapping.getInputForward(); 
   }
  }
  return mapping.findForward(forward);
 }
public ActionMessages check(CalaForm cForm){
  ActionMessages errors = new ActionMessages();
  if("".equals(cForm.getNum1())){
      errors.add("num1",new ActionMessage("error.empty"));
  }
  if("".equals(cForm.getNum2())){
      errors.add("num2",new ActionMessage("error.empty"));
  }
  if("0".equals(cForm.getNum2())){
      errors.add("num2",new ActionMessage("error.divide"));
  }
  return errors;
 }

(4)在caloper.jsp中加如下代码:
第一个数:<html:text property="num1"></html:text><html:errors property="num1"/><br>
第二个数:<html:text property="num2"></html:text><html:errors property="num2"/><br>

4.<html:errors/>
errors.add(ActionMessages.GLOBAL_MESSAGE,new ActionMessage("error.empty.num1"));

5.//判断是否为数字的经典代码  
  boolean isNumeric(String   number)  
  {  
     try  
     {  
        Float.parseFloat(number);  
        return true;  
     }  
     catch(NumberFormatException   sqo)  
     {  
        return false;  
     }  
  }  
   


3月10日
1.action forward
<action path="/login" forward="/login.jsp">

2.input,path里面要加/。

3.plug-in建在 <message-resources的下面
 <plug-in className="com.softeem.plug.LogPlugin"></plug-in>
 建一个logplugin.java implements PlugIn

4.controller
 <!--<controller processorClass="com.softeem.controller.MyRequestProcessor"></controller>-->

5. 语言

6.在form中做页面逻辑验证
在action中做业务逻辑验证

7.validate框架
配validate.xml文件,
  <!DOCTYPE form-validation PUBLIC
          "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0//EN"
          "http://jakarta.apache.org/commons/dtds/validator_1_0.dtd">

form继承validateForm

装插件
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
        <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,
                                                  /WEB-INF/validation.xml"/>
</plug-in>

配action 的validate和input

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE form-validation PUBLIC
          "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0//EN"
          "http://jakarta.apache.org/commons/dtds/validator_1_0.dtd">
<form-validation>
 <formset>
  <form name="loginForm">
   <field property="userName" depends="required,minlength,maxlength">
    <arg0 key="userName" />
    <arg1 name="minlength" key="${var:minlength}"
     resource="false" />
    <arg2 name="maxlength" key="${var:maxlength}"
     resource="false" />
    <var>
     <var-name>minlength</var-name>
     <var-value>2</var-value>
    </var>
    <var>
     <var-name>maxlength</var-name>
     <var-value>8</var-value>
    </var>
   </field>
   <field property="password"
    depends="required,minlength,maxlength">
    <arg0 key="password" />
    <arg1 name="minlength" key="${var:minlength}"
     resource="false" />
    <arg2 name="maxlength" key="${var:maxlength}"
     resource="false" />
    <var>
     <var-name>minlength</var-name>
     <var-value>2</var-value>
    </var>
    <var>
     <var-name>maxlength</var-name>
     <var-value>8</var-value>
    </var>
   </field>
   <field property="hudongjie"
    depends="required,doubleRange,double">
    <arg0 key="hudongjie" />
    <arg1 name="doubleRange" key="${var:min}" resource="false" />
    <arg2 name="doubleRange" key="${var:max}" resource="false" />
    <var>
     <var-name>min</var-name>
     <var-value>0</var-value>
    </var>
    <var>
     <var-name>max</var-name>
     <var-value>100</var-value>
    </var>
   </field>
   <field property="xx"
    depends="mask,required">
    <arg0 key="xx" />
    <var>
     <var-name>mask</var-name>
     <var-value>^1[0-9]{10}$</var-value>
    </var>
   </field>
   <field property="da"
    depends="date,required">
    <arg0 key="da" />
    <var>
     <var-name>datePattern</var-name>
     <var-value>yyyy-MM-dd</var-value>
    </var>
   </field>
  </form>
 </formset>
</form-validation>

 

8.<html:form οnsubmit="return validateLoginForm(this)" action="login.do">
  <html:form action="validate.do" method="post"
    οnsubmit="return ValidateLoginForm(this);" >
   <html:javascript dynamicJavascript="true"
     staticJavascript="false" formName="loginForm"/>

3月11日 hibernate
1.优点
屏蔽数据库之间的差异性
减少代码量
2.什么叫持久化
瞬时状态数据存在内存
持久状态数据存在磁盘
3.orm
表现层-业务逻辑层-持久层
4.hibernate是用JDBC实现持久
5.hibernate的三个步骤
(1)导包
(2)配配置文件
 <hibernate-configuration>

    <session-factory>
        <property name="connection.username">sa</property>
        <property name="connection.url">jdbc:sqlserver://localhost:1433;DatabaseName=willPower</property>
        <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
        <property name="connection.password">198574520</property>
        <property name="connection.driver_class">com.microsoft.jdbc.sqlserver.SQLServerDriver</property> 
        <property name="show_sql">true</property>
        <mapping resource="username.hbm.xml"></mapping>
    </session-factory>
</hibernate-configuration>
(3)配映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="com.softeem.testStruts.pojo.Username" table="username">
<id name="id" type="java.lang.Integer">
<column name="id" ></column>
<generator class="native"></generator>
</id>
<property name="username" type="java.lang.String">
<column name="username" length="30"></column>
</property>
<property name="password" type="java.lang.String">
<column name="password" length="30"></column>
</property>
</class>
</hibernate-mapping>

6.使用hibernate 的7个步骤:
(1)读取配置文件
(2)创建SessionFactory
(3)open Session
(4)开始一个事务
(5)持久化操作
(6)提交事务
(7)关闭Session

public void insert(Object obj){
  Configuration conf=new Configuration().configure();
  SessionFactory sf=conf.buildSessionFactory();
  Session session=sf.openSession();
  Transaction tx=session.beginTransaction();
  session.save(obj);
  tx.commit();
  session.close();
 }

public class BaseHibernateDAO {
 public Session getSession(){
  return HibernateSessionFactory.getSession();
 }
 public void insert(Object obj){
  getSession().save(obj);
 }
 
 public void update(Object obj){
  getSession().update(obj);
 }
 
 public void delete(Object obj){
  getSession().delete(obj);
 }
 
 public Object get(Class clazz, int id){
  Object obj=getSession().get(clazz, id);
  return obj;
 }
 
}

public class UsernameDAO extends BaseHibernateDAO{

 public void insert(Username user){
  super.insert(user);
 }
 
 public void update(Username user){
  super.update(user);
 }
 
 public void delete(Username user){
  super.delete(user);
 }
 
 public Username get(int id){
  return (Username)super.get(Username.class,id);
 }
 
 public static void main(String[] args) {
  UsernameDAO dao = new UsernameDAO();
  Transaction tx = dao.getSession().beginTransaction();
  Username user = new Username();
  user = dao.get(1);
  user.setUsername("周星驰");
  user.setPassword("008");
  dao.update(user);
  tx.commit();
  dao.getSession().close(); 
 }

}


7.实体间的关联
  Set<Street> set = district.getStreets();
  for (Street street : set) {
      System.out.println(street.getStreetName());
  }

  private Set streets = new HashSet(0);
  <set name="streets" inverse="true">
 <key>
  <column name="districtId" />
 </key>
 <one-to-many class="com.softeem.foreign.pojo.Street" />
  </set>
  跟<property/>同等级

  private District district;
  <many-to-one name="district" class="com.softeem.foreign.pojo.District" fetch="select">
      <column name="districtId" />
  </many-to-one>
  跟<property/>同等级

3月12日
1.有外键时,hibernate是采用延时装载机制,当调用street.getDistrict().getDistictName()语句时才加载district属性
 street里面加lazy="false" 默认是true

2.${street.district.districtName}

3.层次概念
表现层:struts,jsf,springmvc
dto:数据传输对象 尽量采用简单数据类型
业务逻辑层:spring,EJB,webservce
pojo:
持久层:hibernate,EJB3.0,ibatis

接口中的方法缺省是abstract可省略。

4.门面模块
分几个servce
 在servce里面把pojo转化为dto

5.hibernate查询语句
为什么使用hql
面向对象的查询


public List<User> findAll(){
   String hql = "from User user";
   return getSession().createQuery(hql).list();
}

public List<User> findById(String userName,String password){
   String hql = "from User user where user.userName=? and user.password=?";
   Query query= getSession().createQuery(hql);
   query.setString(0,userName);
   query.setString(1,password);
   return query.list();
}

public List<User> findById(String userName,String password){
   String hql = "from User user where user.userName LIKE ?";
   Query query= getSession().createQuery(hql);
   query.setString(0,"%"+userName+"%");
   return query.list();
}

BeanUtils.

6.测试HQL语句
from Street street
where street.district.districtName='洪山区'
order by street.streetName

7.分页查询
public List<User> findAll(int curpage,int pageRecords){
   String hql = "from User user";
   Query query= getSession().createQuery(hql);
   query.setFirstResult(curpage);
   query.setMaxResults(pageRecords);
   return query.list(); 
}
10.或其最大页


8.public class SubUserDAO extends UserDAO implements IUserDAO{
}

9.使用Criteria查询
public List<User> findAll(){
   Criteria criteria = getSession().createCriteria(User.class);
   return criteria.add(Restrictions.like("userName","%l%");
}

10..............
assert(pageFrom>0);
criteria
.add(Restrictions.eq("userName","123")
.addOrder(Order.asc("userName"))
.setFirstResult((pageForm-1)*pageRecords)
.setMaxResults(pageRecords)
.list();

11.pojo

瞬时态
持久态
游离态

处于持久态的pojo里面的值改变了之后只要提交事务数据库就会发生改变,不需要调用
update()方法
如果再定义一个pojo和第一个相同的并做了修改,再调用update()方法后提交事务就会有异常。
但调用save方法没有异常。

3月13日
oracle数据库
1.安装oracle数据库
先安database
再装客户端
再装PL/SQL developer
users-ook-objects-tables


2.创建一个表空间look
创建一个用户,设置成管理员权限,在look上
建一个表tb_user,在ook用户上,look表空间上

3.oracle中的字符数据类型
char  定长
raw 存储二进制数据
lob 称为“大对象”数据类型,可以存储多达4GB的非结构化信息,如视频,图片。

4.伪列 rownum  自动加的 用于分页
是动态添加的,在已查询的结果中添加的


5.分页代码

select * from (
select rownum as al ,u.*
from ook.tb_user u
where password like '%3%') u1
where al>2 and al<5;

6.编辑表
alter table ook.tb_user
add (address varchar2(50));

create table ook.tb_user2
as
select * from ook.tb_user;
select * from ook.tb_user2;


7.sqlserver中时间date 2009-03-13
oracle中date  25-5月-05   日 月 年

to date('2009-02-03','yyyy-mm-dd')


insert into tb_user select * from tb_user1;

commit;
8.事务控制语言

9.算数操作符

10.比较运算符
=
不等于
sqlserver <>
oracle !=

11.集合运算符
select * from ook.tb_user where user_name='tianqi'
union
select * from ook.tb_user where user_name='zhaoliu';

12.连接运算符


13.sql函数
日期函数
add_months(time,1)
last_day
字符函数

数字函数


转换函数
select u.* ,to_char(birth_day,'yyyy"年"mmdd')
from tb_user u where id=1;

to_number

to_date('2009-02-05','yyyy-mm-dd')

NVL
NVL2

分组函数

select count(*) from student group by greade

select count(*) , greade from student group by greade

long 是text类型

14.序列

INSERT INTO ook.tb_user values(
ook.seq_user_id.nextval,
'wangba',
'123',
'a');
select * from ook.tb_user;

15.pl/sql语法

标识符不能超过30个字符
第一个字符是字母


declare
  Ename varchar2(30) :='king';
  bigin

  end

用%type匹配保持类型一致


declare
  v_empno

16.存储过程

添加用户的存储过程
create or replace procedure ook.sp_user_insert
(v_user_name  varchar2,
v_password varchar2)
is
NullException Exception;
begin
  if v_user_name is not null then
  insert into ook.tb_user(id,user_name,password)
  values(ook.seq_user_id.nextval,v_user,v_password);
  else
     raise NullException;
end if;
EXCEPTION
   when NullException then
    dbms  output.put line('user name is null')
end;

command window
执行存储过程
execute ook.sp_user_insert('','');

循环

declare
 x number := 1;
 begin
     where x<100 loop
     insert into ook.tb_user
     values(ook.seq_user_id.nextval,'zhangsan','123','345');
     x:=x+1;
end loop;
end;


if x<50 then

  else

end if;

if v_user_name is not null then

异常
raise NullException  ;
exception
  when NullException  then

3月16日
1.查询语句

2.调用存储过程

 CREATE OR REPLACE PACKAGE OOK.MyPackage
IS
    TYPE RET_CURSOR IS ref cursor;
END;

CREATE OR REPLACE PROCEDURE OOK.SP_USER_UPDATE
(v_id number,
v_user_name varchar2,
v_password varchar2,
v_address varchar2,
v_birthday date)
IS
BEGIN
    UPDATE OOK.TB_USER SET
        USER_NAME = v_user_name,
        PASSWORD = v_password,
        ADDRESS = v_address,
        BIRTH_DAY = v_birthday
    WHERE ID = V_id;
END;


CREATE OR REPLACE PROCEDURE OOK.SP_USER_INSERT
(v_user_name varchar2,
v_password varchar2,
v_address varchar2,
v_birthday date)
IS
BEGIN
    INSERT INTO OOK.TB_USER(ID, USER_NAME, PASSWORD, ADDRESS, BIRTH_DAY)
    VALUES(OOK.SEQ_USER_ID.NEXTVAL,v_user_name, v_password, v_address, v_birthday);
END;


CREATE OR REPLACE PROCEDURE OOK.SP_USER_FINDALL
(p_cursor out OOK.MyPackage.RET_CURSOR)
IS
BEGIN
    OPEN p_cursor FOR
    SELECT * FROM OOK.Tb_User;
END;


CREATE OR REPLACE PROCEDURE OOK.SP_USER_DELETE
(v_id number)
IS
BEGIN
    DELETE FROM OOK.TB_USER
    WHERE ID = V_id;
END;


调用存储过程jdbc

package com.softeem.struts.dao;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.softeem.struts.pojo.User;

public class UserDAO {
 public List<User> findAll(){
  List<User> list = new ArrayList<User>();
  try {
   Class.forName("oracle.jdbc.driver.OracleDriver");
   String url = "jdbc:oracle:thin:@localhost:1521:orcl";
   Connection conn = DriverManager.getConnection(url,"ook","softeem1");
   
   CallableStatement cs = conn.prepareCall(
     "{call SP_USER_FINDALL(?)}");
   cs.registerOutParameter(1, oracle.jdbc.OracleTypes.CURSOR);
   cs.execute();
   ResultSet rs = (ResultSet)cs.getObject(1);
   while(rs.next()){
    User user = new User();
    user.setUserName(rs.getString("user_name"));
    user.setPassword(rs.getString("password"));
    user.setAddress(rs.getString("address"));
    user.setBirthday(rs.getDate("birth_day"));
    list.add(user);
   }
   rs.close();
   cs.close();
   conn.close();
   
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return list;
 }
 
 public void insert(User user){
  try {
   Class.forName("oracle.jdbc.driver.OracleDriver");
   String url = "jdbc:oracle:thin:@localhost:1521:orcl";
   Connection conn = DriverManager.getConnection(url,"ook","softeem1");
   
   CallableStatement cs = conn.prepareCall("{call SP_USER_INSERT(?,?,?,?)}");
   cs.setString(1, user.getUserName());
   cs.setString(2, user.getPassword());
   cs.setString(3, user.getAddress());
   cs.setDate(4, new java.sql.Date(user.getBirthday().getTime()));
   cs.executeUpdate();
   
   cs.close();
   conn.close();
   
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
 }
 
 public static void main(String[] args){
  UserDAO dao = new UserDAO();
  System.out.println(dao.findAll());
//  User user = new User();
//  user.setUserName("helo");
//  user.setPassword("123456");
//  user.setAddress("wuhan");
//  user.setBirthday(new Date());
//  dao.insert(user);
 }
}


3.主键自增长
  <id name="id" type="java.lang.Integer">
  <column name="id" />
- <generator class="sequence">
  <param name="sequence">SEQ_USER_ID</param>
  </generator>
  </id>

 

4.session.clear();
session.
 session一级缓存

get()和load()的区别

5.Action作用:
将页面数据放到service中,从service中得数据送到页面

6.service用spring框架做
spring AOP面向切面/方面编程
Spring MVC
Spring Web
Spring ORM
Spring DAO
Spring Context
Spring Core(核心)

7.用sping创建对象
(1)建一个BookService.java
package service;

public interface BookService {
 public abstract void sayHello();
}
(2)建一个BookServiceImpl.java
package service;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BookServiceImpl implements BookService {
 private String welcome;

 public String getWelcome() {
  return welcome;
 }

 public void setWelcome(String welcome) {
  this.welcome = welcome;
 }

 public void sayHello() {
  // TODO Auto-generated method stub
  System.out.println(welcome);
 }
 public static void main(String[] args){
  ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  BookService service = (BookService)context.getBean("bookService");
  service.sayHello();
 }

}

方法2 ClassPathResource resource = new ClassPathResource("hello.xml");
      XmlBeanFactory factory = new XmlBeanFactory(resource);
      GreetingService greetingService = (GreetingService)factory.getBean("greetingService");
      greetingService.sayGreeting();
 

方法3 InputStream fin = new FileInputStream(“hello.xml");
      BeanFactory factory = new XmlBeanFactory(fin);
      GreetingService greetingService = (GreetingService)
      factory.getBean("greetingService");
      greetingService.sayGreeting();
      fin.close();

方法4 ApplicationContext context = new
      FileSystemXmlApplicationContext("c:/foo.xml");
      context.getBean(“helloService”);

方法5 ApplicationContext context = new
      ClassPathXmlApplicationContext("foo.xml");
      context.getBean(“helloService”);
(3)配置applicationContext.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans
 xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    <bean id="bookService" class="service.BookServiceImpl">
    <property name="welcome">
    <value>hello world</value>
    </property>
    </bean>

</beans>

12.是否公用一个类
 <bean
    id="studentDao" class="com.springinaction.training.service.StudentDaoImpl" singleton="false"/>

13.Inner beans

      <bean id="courseService“ class="com.softeem.spring.service.CourseServiceImpl">
      <property name="studentService">
        <bean id=“studentService”
        class="com.softeem.spring.service.StudentServiceImpl"/>
      </property>
      </bean>

14.Injecting dependencies via constructor

 <bean
    id="studentService“ class="com.softeem.spring.service.StudentS
    erviceImpl">
     <constructor-arg><ref
        bean="studentDao"/></constructor-arg>
 </bean>

8.注入IOC

<bean id="bookService" class="service.BookServiceImpl">
     <property name="userDAO">
        <ref bean="userDAO"/>
     </property>
</bean>
集合注入

Properties emails=new Properties();
<property name="emails">
<props>
   <prop key="zhangsan">zhangsan@yahoo.com</prop>
   <prop key="zhangsan">zhangsan@yahoo.com</prop>
   <prop key="zhangsan">zhangsan@yahoo.com</prop>
</props>
</property>


<property name="address">
<list>
   <value>wuhan</value>
   <value>wuhan</value>
   <value>wuhan</value>
</list>
</property>

<property name="map">
  <map>
     <entry>
       <key></key>
       <value></value>
     </entry>
  </map>
</property>

15.ContextLoaderPlugin
(1)set the type of this action
 Modify the struts-config.xml file.

 <action path="/user"
    type="org.springframework.web.struts.DelegatingActi
    onProxy “ name="userForm" scope="request"
    validate="false" parameter="method">
     <forward name="list" path="/userList.jsp"/>
     <forward name="edit"
        path="/userForm.jsp"/>
 </action>

 (2) configure your struts-config.xml

 <plug-in
    className="org.springframework.web.struts.ContextL
    oaderPlugIn">
    <set-property
    property="contextConfigLocation“ value="/WEB-
    INF/action-servlet-account.xml" />
 </plug-in>

 (3)define your Action in a context file

 <bean id="accountService"
    class="org.bicool.crm.service.AccountService"/>
 <bean name="/user" singleton="false"
    autowire="byName“ class="org.bicool.crm.framework.
    AccountProcessAction"/>
    <property name="accountService">
          <ref  bean="accountService"/>
    </property>
 </ bean >

9.单子模式
package com.softeem.struts.service;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ApplicationContextFactory {
 static ApplicationContext context;
 public static ApplicationContext getContext(){
  if(context == null){
   context = new ClassPathXmlApplicationContext("applicationContext.xml");
  }
  return context;
 }
}

10.用Spring给hibernate的session赋值

<bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="configLocation"
   value="classpath:hibernate.cfg.xml">
  </property>
 </bean>


11.  <?xml version="1.0" encoding="UTF-8" ?>
- <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
- <bean id="bokeService" class="com.softeem.struts.service.BokeServiceImpl">
- <constructor-arg>
  <ref bean="userDAO" />
  </constructor-arg>
- <property name="userDAO">
  <ref bean="userDAO" />
  </property>
- <property name="emails">
- <props>
  <prop key="zhangsan">zhangsan@hotmail.com</prop>
  <prop key="lisi">lisi@hotmail.com</prop>
  <prop key="wangwu">wangwu@hotmail.com</prop>
  </props>
  </property>
- <property name="address">
- <list>
  <value>wuhan</value>
  <value>changsa</value>
  <value>beijing</value>
  </list>
  </property>
- <property name="map">
- <map>
- <entry>
- <key>
  <value>zhangsan</value>
  </key>
  <value>13987877883</value>
  </entry>
- <entry>
- <key>
  <value>lisi</value>
  </key>
  <value>13768765432</value>
  </entry>
  </map>
  </property>
  </bean>
- <bean id="userDAO" class="com.softeem.struts.pojo.SubUserDAO">
- <property name="sessionFactory">
  <ref bean="sessionFactory" />
  </property>
  </bean>
- <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="configLocation" value="classpath:hibernate.cfg.xml" />
  </bean>
  </beans>

3月17日
1.spring AOP面向切面/方面编程,面向应用编程
context = new WebApplicationContext

servletContext    服务器启动到服务器关闭

2.http://www.soit.com.cn
scope=""

3.getcurrentSession();

 

4.<bean autowire="byName" id="bokeService" class="">
</bean>
自动装配

5.AOP的两种配置方案
(1)
<?xml version="1.0" encoding="UTF-8"?>
<beans
 xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 <bean name="/login" class="com.softeem.struts.action.LoginAction">
  <property name="bokeService" ref="bokeServiceProxy"></property>
 </bean>

        <bean id="bokeServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
  <property name="proxyInterfaces">
   <value>com.softeem.struts.service.BokeService</value>
  </property>
  <property name="target" ref="bokeService"></property>
  <property name="interceptorNames">
        <list><value>TransactionAdvisor</value></list>
     </property>
 </bean>
       
        <bean id="TransactionAdvisor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
  <property name="advice" ref="TransactionAdvice"></property>
  <property name="mappedNames">
   <list>
    <value>insert*</value>
   </list>
  </property>
 </bean>
        
        <bean id="TransactionAdvice" class="com.softeem.struts.service.TransactionAdvice"/>

        <bean  id="bokeService" class="com.softeem.struts.service.BokeServiceImpl">  
  <property name="userDAO">
   <ref bean="userDAO"/>
  </property>
  <property name="bokeDAO">
   <ref bean="bokeDAO"/>
  </property>  
 </bean>
 
 <bean id="bokeDAO" class="com.softeem.struts.pojo.SubBokeDAO">
  <property name="sessionFactory">
   <ref bean="sessionFactory"/>
  </property>
 </bean> 
 
 <bean id="userDAO" class="com.softeem.struts.pojo.SubUserDAO">
  <property name="sessionFactory">
   <ref bean="sessionFactory"/>
  </property>
 </bean> 
 
 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="configLocation"
   value="classpath:hibernate.cfg.xml">
  </property>
 </bean>
 
</beans>

(2)
        <bean
  class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
  <property name="beanNames">
   <value>*Service</value>
  </property>
  <property name="interceptorNames">
  <list>
   <value>TransactionAdvisor</value>
  </list>
  </property>
 </bean>
       
        <bean id="TransactionAdvisor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
  <property name="transactionManager" ref="transactionManager" />
  <property name="transactionAttributes">
   <props>
    <prop key="insert*">PROPAGATION_REQUIRED</prop>
   </props>
  </property> 
 </bean>
         
        <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory"></property>
 </bean>
 
6.sessionFactory.getCurrentSession();
 单子模式,用transactionManager做事务的时候用这个方法获取session
 
7.<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
  <set-property property="contextConfigLocation" value="classpath:applicationContext.xml" />
 </plug-in>


3月20日
DWR
1.
   <script type="text/javascript" src="dwr/interface/HelloWorldService.js"></script>
 <script type="text/javascript" src="dwr/interface/BokeService.js"></script>
 <script type="text/javascript" src="dwr/util.js"></script>
 <script type="text/javascript" src="dwr/engine.js"></script>

 <script type="text/javascript"> 
 window.onload = function(){
  $("button1").onclick = function(){
   BokeService.login($("userName").value, $("password").value, function(item){
    if(item != null){
        alert(item.userName);
        alert(item.password);
    }
   });
  }
 }
 </script>

 

 

 

 

 

 

 

 

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java笔记是由北京大学青鸟教育推出的一款专门针对Java语言的学习工具。它以全面、系统、实践为特点,通过详细的代码示例和清晰的讲解,帮助学习者全面掌握Java编程语言。 Java笔记采用了线上与线下相结合的学习模式。学员可以通过手机、平板电脑、电脑等设备在线学习,还可以在学习过程中随时记录自己的学习笔记。同时,北大青鸟还为学员提供线下实践环境,学员可以在实验室里亲自动手实践所学知识,加深理解和应用。 Java笔记的内容非常全面,包括了Java语言的基本语法、面向对象编程、异常处理、流操作、多线程、数据库操作等众多知识点。除了理论知识,Java笔记还提供了大量的实例代码,可供学员参考和模仿。这样的学习方式既帮助学员理解Java的基本概念,又能让他们运用所学知识解决实际问题。 与此同时,Java笔记还注重学员的互动交流。在学习过程中,学员可以利用笔记功能记录学习心得和疑惑,还可以在论坛上与其他学员进行讨论和交流。这种互动形式既能促进学员之间的学习互助,也能更好地帮助学员理解和应用所学知识。 总之,Java笔记是北大青鸟推出的一款专注于Java语言学习的工具,通过系统的课程设置、丰富的实例代码和互动交流的方式,帮助学员全面掌握Java编程知识,提升编程能力。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值