为了正常的体验网站,请在浏览器设置里面开启Javascript功能!

全国计算机二级java学习资料大全

2011-01-17 50页 doc 261KB 43阅读

用户头像

is_359615

暂无简介

举报
全国计算机二级java学习资料大全微软资格认证考试 >> 考试辅导 由易到难,MCSE最佳考试顺序 Eclipse+JBoss+EJB3的SessionBean注释方法 有时需要在Session Bean中初始化和释放一些资源。这些工作应该在SessionBean的@PostConstruct和@PreDestroy方法中进行。其中用 @PostConstruct注释的方法在SessionBean的构造方法调用之后以后EJB容器在处理完一些其他工作后调用。用 @PreDestroy注释的方法在SessionBean的对象实例被EJB容器销毁之前调用。   除此...
全国计算机二级java学习资料大全
微软资格认证考试 >> 考试辅导 由易到难,MCSE最佳考试顺序 Eclipse+JBoss+EJB3的SessionBean注释方法 有时需要在Session Bean中初始化和释放一些资源。这些工作应该在SessionBean的@PostConstruct和@PreDestroy方法中进行。其中用 @PostConstruct注释的方法在SessionBean的构造方法调用之后以后EJB容器在处理完一些其他工作后调用。用 @PreDestroy注释的方法在SessionBean的对象实例被EJB容器销毁之前调用。   除此之外,当有状态的SessionBean存在一定时间未被调用时,EJB容器会将该SessionBean对象钝化(Passivate),也就是保存在硬盘中。当再次访问时,EJB容器会激法该SessionBean。在这两种情况下,EJB容器会分别调用 SessionBean的 @PrePassivate和@PostActivate方法。可以在@PrePassivate方法中将sessionbean中的资源保存或释放,如打开的数据库连接等。在@PostActivate方法中可以恢复相应的资源。如下面的代码所示: package service;     import java.util.ArrayList;   import java.util.List;   import javax.annotation.PostConstruct;   import javax.annotation.PreDestroy;   import javax.annotation.Resource;   import javax.ejb.PostActivate;   import javax.ejb.PrePassivate;   import javax.ejb.SessionContext;   import javax.ejb.Stateful;     @Stateless   public class ShoppingCartBean implements ShoppingCart   {       private List shoppingCart = new ArrayList();       @Resource       private SessionContext sessionContext;              public ShoppingCartBean()       {           System.out.println("constructor:" + sessionContext);       }       @PrePassivate       public void MyPassivate()       {           System.out.println("passivate");       }       @PostConstruct       public void init()       {           System.out.println(sessionContext.getInvokedBusinessInterface());     }       @PreDestroy       public void destory()       {           System.out.println("destory");       }       @PostActivate       public void start()       {           System.out.println("start");       }       @Override       public void addCommodity(String value)       {                      shoppingCart.add(value);       }       @Override       public List getCommodity()       {           return shoppingCart;       }       }  hibernate关系映射 对象-关系 映射基础   1.对象间的基本关系   关联关系:关联关系在设计模式中是被提倡优先使用于继承关系的。关联关系就是将一个对象做为别一个对象的成员,是一种包含的关系。   依赖关系:对与对象之间的方法的调用,不存在包含的关系。   聚集关系:这个关系比较有趣,比如人的手和身体。如果身体不存在了,手也就不存在了。是一种整个与部分的关系。   一般关系:就是继承关系。   上边的这四种关系是对前一天的补充。对象-关系的映射基础没有涉及这些,而是单一对象通过hibernate与数据库的映射关系。    2.持久化类的属性及访问方法   首先回顾一下持久化,我们知道持久化层是从业务逻辑层中分离出来的专门用于数据库操作的这些部分。持久化层中的持久化类,便是我们之前早已学习的domain类。   1).持久化类的访问者有两个,一是JAVA应用程序,二是hibernate。   写:Java应用程序通过setter设置持久化对象的属性,hibernate通过getter获取持久化对象的属性并生成相应的SQL语句对格进行操作。   读:hibernate通过setter设置持久化对象的属性,Java应用程序通过getter获取持久化对象的属性。   2).基本数据类型和包装类型   通过前天的日志,我们知道关联对象的属性与表格的字段是通过property元素节点设置的:    基本的type是hibernate的类型,我们在持久化类中定义的gender属性为int。定义为int类型会有什么弊端?比如,我们有个学生成绩表。如果某个学生没有参加某一学科的考试,但我们却使用了int类型,它的默认值为0,当查看学生成绩时,他到底是考了0分还是没有考试?所以最好将持久化类中的gender属性定义为Integer,它的默认值为null。查询成绩时看到的是null,那么他肯定是没参加考试哦!(注意:数据库中的对应字段应该为字符型)   3).hibernate访问持久化类属性的策略   Hibernate通过name指定的值访问持久化对象。Hibernate通过name值,反射持久化对象的对方法。比如,name的值为 gender。Hibernate会直接反射持久化对象的getGender和setGender方法。所以我们必须保证持久化对象中有对应的方法。这是因为property有一个access属性,它的默认值为property。 如果指定access的值为field,则hibernate直接根据name值反射持久化对象的属性。此时,我们必须保证持久化对象中有对应的属性。   4).在持久化类的方法中加入程序逻辑   通过3)我们知道,如果access的值为property,hibernate直接反射持久化对象的方法。在这个方法中我们就可以加入程序逻辑。老徐举了一个生动的例子,比如Customer类中有firstname和lastname两个属性。但我们只想让hibernate通过 getName方法获得一个firstname+lastname的字符串,此时我们就可以在getName方法中将firstname与 lastname两个属性值合并为一个中间使用 “.”连接的字符串返回。 使用hibernate获取数据表中的数据时,hibernate会调用持久化对象的setName方法。我们在这个方法中将传递进来的参数使用“.”分隔,然后分别设置到firestname和lastname属性中。   5).hibernate的hql语句   我们在使用JDBC、DBUtil时使用的都是SQL语句。但hibernate比较特殊,它使用的是自己的一套东西叫hql语句。比如我们调用session.find方法,传递的hql语句为:   "from customer as c where c.name='itcast'" 其中的customer指向持久化对象的映射文件,name指向持久化对象的映射文件中的property元素的name属性。此时需要注意access属性的值。   6).设置派生属性   Property元素中,有一个formula属性。它的值是一个sql表达式,hibernate将根据此表达式计算的值设置到持久化对象的属性上。比如,我们要统计订单表中的总计:    Hibernate一对多单向关系 1.   数据库schema   Teachers表:   create table TEACHERS   (   ID          NUMBER(10) not null,   TEACHERNAME VARCHAR2(15)   )   alter table TEACHERS   add constraint DERE primary key (ID)   Students表:   create table STUDENTS   (   ID          NUMBER(10) not null,   STUDENTNAME VARCHAR2(15),   TEACHER_ID  NUMBER(10)   )   alter table STUDENTS   add constraint RERE primary key (ID)   alter table STUDENTS   add constraint FFF foreign key (TEACHER_ID)   references TEACHERS (ID);   2.   Teacher.java和Student.java   Teacher.java   package mypack;   public class Teacher {   //教师id   private Long id;   //教师名称   private String teacherName;   /**   * 缺省构造函数   */   public Teacher() {   }   /**   * 得到教师id   * @return Long    教师id   */   public Long getId() {   return id;   }   /**   * 设置教师id   * @param id Long    教师id   */   public void setId(Long id) {   this.id = id;   }   /**   * 得到教师名称   * @return String    教师名称   */   public String getTeacherName() {   return teacherName;   }   /**   * 设置教师名称   * @param teacherName String    教师名称   */   public void setTeacherName(String teacherName) {   this.teacherName = teacherName;   }   /**   * 构造函数   * @param teacherName String   */   public Teacher(String teacherName) {   this.teacherName = teacherName;   }   }   Student.java   package mypack;   public class Student {   //学生id   private Long id;   //学生名称   private String studentName;   //教师类   private Teacher teacher;   /**   * 缺省构造函数   */   public Student() {   }   /**   * 得到学生id   * @return Long    学生id   */   public Long getId() {   return id;  /**   * 设置学生id   * @param id Long    学生id   */   public void setId(Long id) {   this.id = id;   }   /**   * 得到学生名称   * @return String    学生名称   */   public String getStudentName() {   return studentName;   }   /**   * 设置学生名称   * @param studentName String    学生名称   */   public void setStudentName(String studentName) {   this.studentName = studentName;   }   /**   * 得到教师对象   * @return Teacher    教师对象   */   public Teacher getTeacher() {   return teacher;   }   /**   * 设置教师对象   * @param teacher Teacher    教师对象   */   public void setTeacher(Teacher teacher) {   this.teacher = teacher;   }   /**   * 构造函数   * @param string String   * @param teacher Teacher   */   public Student(String studentName, Teacher teacher) {   this.studentName = studentName;   this.teacher = teacher;   }   }   3.   hibernate.properties   ## Oracle   hibernate.dialect net.sf.hibernate.dialect.Oracle9Dialect   hibernate.dialect net.sf.hibernate.dialect.OracleDialect   hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver   hibernate.connection.username jbcm   hibernate.connection.password jbcm   hibernate.connection.url jdbc:oracle:thin:@localhost:1521:wsy   4.   Teacher.hbm.xml和Student.hbm.xml   Teacher.hbm.xml                                       Student.hbm.xml                                       5.   数据库操作类   BusinessService.java   package mypack;   import net.sf.hibernate.*;   import net.sf.hibernate.cfg.Configuration;   import java.util.*;   public class BusinessService{   //session工厂类   public static SessionFactory sessionFactory;   //实始化session工厂   static{   try{   //建立配置类,添加Student类和Teacher类   Configuration config = new Configuration();   config.addClass(Student.class)   .addClass(Teacher.class);   //得到sessionFactory对象   sessionFactory = config.buildSessionFactory();   }catch(Exception e){e.printStackTrace();}   }   /**   * 通过学生类,查找教师类   * @param student Student   * @throws Exception   * @return List   */   public List findTeacherByStudent(Student student) throws Exception{   Session session = sessionFactory.openSession();   Transaction tx = null;   try {   tx = session.beginTransaction();   List orders=(List)session.find("from Student as o where o.teacher.id="+student.getId());   tx.commit();   return orders;   }catch (Exception e) {   if (tx != null) {   tx.rollback();   }   throw e;   } finally {   session.close();   }   }   /**   * 查找指定id的学生类   * @param student_id long   * @throws Exception   * @return Student   */   public Student findStudent(long student_id) throws Exception{   Session session = sessionFactory.openSession();   Transaction tx = null;   try {   tx = session.beginTransaction();   Student student=(Student)session.load(Student.class,new Long(student_id));   tx.commit();   return student;   }catch (Exception e) {   if (tx != null) {   //发生错误,回滚   tx.rollback();   }   throw e;   } finally {   //没有错误,关闭session   session.close();   }   } /**   * 级连保存Teacher对象和Student对象   * @throws Exception   */   public void saveTeacherAndStudentWithCascade() throws Exception{   Session session = sessionFactory.openSession();   Transaction tx = null;   try {   tx = session.beginTransaction();   Teacher teacher=new Teacher("myTeacher");   Student student1=new Student("student1",teacher);   Student student2=new Student("student2",teacher);   session.save(student1);   session.save(student2);   tx.commit();   }catch (Exception e) {   if (tx != null) {   //发生错误,回滚   tx.rollback();   }   e.printStackTrace();   } finally {   // 没有错误,关闭session   session.close();   }   }   /**   * 保存教师和学生对象   * @throws Exception   */   public void saveTeacherAndStudent() throws Exception{   Session session = sessionFactory.openSession();   Transaction tx = null;   try {   tx = session.beginTransaction();   Teacher teacher=new Teacher("teacher1");   session.save(teacher);   Student student1=new Student("student001",teacher);   Student student2=new Student("student002",teacher);   session.save(student1);   session.save(student2);   //提交事务   tx.commit();   }catch (Exception e) {   if (tx != null) {   //发生错误,回滚   tx.rollback();   }   throw e;   } finally {   // 没有错误,关闭session   session.close();   }   }   /**   * 输出学生对象集合   * @param students List   */   public void printStudents(List students){   for (Iterator it = students.iterator(); it.hasNext();) {   Student student=(Student)it.next();   System.out.println("OrderNumber of "+student.getTeacher().getTeacherName()+ " :"+student.getStudentName());   }   }   /**   * 测试方法   * @throws Exception   */   public void test() throws Exception{   saveTeacherAndStudent();   //      saveTeacherAndStudentWithCascade();   //      Student student=findStudent(1);   //      List students=findTeacherByStudent(student);   //      printStudents(students);   }   public static void main(String args[]) throws Exception {   new BusinessService().test();   sessionFactory.close();   }   }   目录结构示意:   Classes   Hibernate.property   /mypack   Teacher.java   Student.java   BusinessService.java   Teacher.hbm.xml   Student.hbm.xml J2me中实现StringTokenizer的功能 由于Java ME 中没有StringTokenizer,而我们又经常使用StringTokenizer的功能!而事实上,在rms的读取数据过程中经常会用到字符串的分割。这样没有!我们就只好编写一个类,代码如下:   ps:编译一下,然后引入编译器!写个实例!运行可见结果!但需注意此类中方法的使用!   import java.util.*;   public class StringTokenizer implements Enumeration   {   private void setMaxDelimChar()   {   if(delimiters == null)   {   maxDelimChar = '\0';   return;   }   char c = '\0';   for(int i = 0; i < delimiters.length(); i++)   {   char c1 = delimiters.charAt(i);   if(c < c1)   c = c1;   }   maxDelimChar = c;   }   public StringTokenizer(String s, String s1, boolean flag)   {   currentPosition = 0;   newPosition = -1;   delimsChanged = false;   str = s;   maxPosition = s.length();   delimiters = s1;   retDelims = flag;   setMaxDelimChar();   }   public StringTokenizer(String s, String s1)   {   this(s, s1, false);   } public StringTokenizer(String s)   {   this(s, " \t\n\r\f", false);   }   private int skipDelimiters(int i)   {   if(delimiters == null)   throw new NullPointerException();   int j;   for(j = i; !retDelims && j < maxPosition; j++)   {   char c = str.charAt(j);   if(c > maxDelimChar || delimiters.indexOf(c) < 0)   break;   }   return j;   }   private int scanToken(int i)   {   int j;   for(j = i; j < maxPosition; j++)   {   char c = str.charAt(j);   if(c <= maxDelimChar && delimiters.indexOf(c) >= 0)   break;   }   if(retDelims && i == j)   {   char c1 = str.charAt(j);   if(c1 <= maxDelimChar && delimiters.indexOf(c1) >= 0)   j++;   }   return j;   } public boolean hasMoreTokens()   {   newPosition = skipDelimiters(currentPosition);   return newPosition < maxPosition;   }   public String nextToken()   {   currentPosition = newPosition < 0 || delimsChanged ? skipDelimiters(currentPosition) : newPosition;   delimsChanged = false;   newPosition = -1;   if(currentPosition >= maxPosition)   {   throw new NoSuchElementException();   } else   {   int i = currentPosition;   currentPosition = scanToken(currentPosition);   return str.substring(i, currentPosition);   }   }   public String nextToken(String s)   {   delimiters = s;   delimsChanged = true;   setMaxDelimChar();   return nextToken();   }   public boolean hasMoreElements()   {   return hasMoreTokens();   } public Object nextElement()   {   return nextToken();   }   public int countTokens()   {   int i = 0;   for(int j = currentPosition; j < maxPosition;)   {   j = skipDelimiters(j);   if(j >= maxPosition)   break;   j = scanToken(j);   i++;   }   return i;   }   private int currentPosition;   private int newPosition;   private int maxPosition;   private String str;   private String delimiters;   private boolean retDelims;   private boolean delimsChanged;   private char maxDelimChar;   } JavaIO读取文件中文乱码问题 1、JAVA读取文件,避免中文乱码。   /**   * 读取文件内容   *   * @param filePathAndName   String  读取文件路径   * @return String  文件中的内容   */   public static String readFile(String filePathAndName) {   String fileContent = "";   try {   File f = new File(filePathAndName);   if(f.isFile()&&f.exists()){   InputStreamReader read = new InputStreamReader(new FileInputStream(f),"UTF-8");   BufferedReader reader=new BufferedReader(read);   String line;   while ((line = reader.readLine()) != null) {   fileContent += line;   }   read.close();   }   } catch (Exception e) {   System.out.println("读取文件内容操作出错");   e.printStackTrace();   }   return fileContent;   } 2、JAVA写入文件,避免中文乱码。   /**   * 写文件   *   * @param filePathAndName   String  写文件路径   * @param fileContent   String  需要写入的内容   */   public static void writeFile(String filePathAndName, String fileContent) {   try {   File f = new File(filePathAndName);   if (!f.exists()) {   f.createNewFile();   }   OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f),"UTF-8");   BufferedWriter writer=new BufferedWriter(write);   //PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filePathAndName)));   //PrintWriter writer = new PrintWriter(new FileWriter(filePathAndName));   writer.write(fileContent);   writer.close();   } catch (Exception e) {   System.out.println("写文件内容操作出错");   e.printStackTrace();   }   } JavaMap遍历速度最优解 第一种:   Map map = new HashMap();   Iterator iter = map.entrySet().iterator();   while (iter.hasNext()) {   Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey();   Object val = entry.getValue();   }   效率高,以后一定要使用此种方式!   第二种:   Map map = new HashMap();   Iterator iter = map.keySet().iterator();   while (iter.hasNext()) {   Object key = iter.next();   Object val = map.get(key);   }   效率低,以后尽量少使用!   HashMap的遍历有两种常用的方法,那就是使用keyset及entryset来进行遍历,但两者的遍历速度是有差别的,下面请看实例:   public class HashMapTest {   public static void main(String[] args) ...{   HashMap hashmap = new HashMap();   for (int i = 0; i < 1000; i ) ...{   hashmap.put("" i, "thanks");   } long bs = Calendar.getInstance().getTimeInMillis();   Iterator iterator = hashmap.keySet().iterator();   while (iterator.hasNext()) ...{   System.out.print(hashmap.get(iterator.next()));   }   System.out.println();   System.out.println(Calendar.getInstance().getTimeInMillis() - bs);   listHashMap();   }   public static void listHashMap() ...{   java.util.HashMap hashmap = new java.util.HashMap();   for (int i = 0; i < 1000; i ) ...{   hashmap.put("" i, "thanks");   }   long bs = Calendar.getInstance().getTimeInMillis();   java.util.Iterator it = hashmap.entrySet().iterator();   while (it.hasNext()) ...{   java.util.Map.Entry entry = (java.util.Map.Entry) it.next();   // entry.getKey() 返回与此项对应的键   // entry.getValue() 返回与此项对应的值   System.out.print(entry.getValue());   }   System.out.println();   System.out.println(Calendar.getInstance().getTimeInMillis() - bs);   }   }   对于keySet其实是遍历了2次,一次是转为iterator,一次就从hashmap中取出key所对于的value。而entryset只是遍历了第一次,他把key和value都放到了entry中,所以就快了。   注:Hashtable的遍历方法和以上的差不多! JAVASCRIPT中修改CSS 1.js修改单个元素的css属性   document.getElementByIdx('obj').className=”…”,   document.getElementByIdx('obj').style.backgroundColor=”#003366″ ,   2.js修改整个页面的css属性         3.js和css的style属性对照表   盒子标签和属性对照   CSS语法 (不区分大小写) JavaScript语法 (区分大小写)   border border   border-bottom borderBottom   border-bottom-color borderBottomColor   border-bottom-style borderBottomStyle   border-bottom-width borderBottomWidth   border-color borderColor   border-left borderLeft   border-left-color borderLeftColor   border-left-style borderLeftStyle   border-left-width borderLeftWidth   border-right borderRight   border-right-color borderRightColor   border-right-style borderRightStyle   border-right-width borderRightWidth   border-style borderStyle   border-top borderTop   border-top-color borderTopColor   border-top-style borderTopStyle   border-top-width borderTopWidth   border-width borderWidth   clear clear   float floatStyle   margin margin   margin-bottom marginBottom   margin-left marginLeft   margin-right marginRight   margin-top marginTop   padding padding   padding-bottom paddingBottom   padding-left paddingLeft   padding-right paddingRight   padding-top paddingTop   颜色和背景标签和属性对照   CSS语法 (不区分大小写) JavaScript语法 (区分大小写)   background background   background-attachment backgroundAttachment   background-color backgroundColor   background-image backgroundImage   background-position backgroundPosition   background-repeat backgroundRepeat   color color 样式标签和属性对照   CSS语法 (不区分大小写) JavaScript语法 (区分大小写)   display display   list-style-type listStyleType   list-style-image listStyleImage   list-style-position listStylePosition   list-style listStyle   white-space whiteSpace   文字样式标签和属性对照   CSS语法 (不区分大小写) JavaScript语法 (区分大小写)   font font   font-family fontFamily   font-size fontSize   font-style fontStyle   font-variant fontVariant   font-weight fontWeight   文本标签和属性对照   CSS语法 (不区分大小写) JavaScript语法 (区分大小写)   letter-spacing letterSpacing   line-break lineBreak   line-height lineHeight   text-align textAlign   text-decoration textDecoration   text-indent textIndent   text-justify textJustify   text-transform textTransform   vertical-align verticalAlign   4.引起css改变的js事件   HTML 4.0 的新特性之一是有能力使 HTML 事件触发浏览器中的动作(action),比如当用户点击某个 HTML 元素时启动一段 JavaScript。下面是一个属性列表,这些属性可插入 HTML 标签来定义事件动作。   FF: Firefox, N: Netscape, IE: Internet Explorer 属性 当以下情况发生时,出现此事件 FF N IE onabort 图像加载被中断 1 3 4 onblur 元素失去焦点 1 2 3 onchange 用户改变域的内容 1 2 3 onclick 鼠标点击某个对象 1 2 3 ondblclick 鼠标双击某个对象 1 4 4 onerror 当加载文档或图像时发生某个错误 1 3 4 onfocus 元素获得焦点 1 2 3 onkeydown 某个键盘的键被按下 1 4 3 onkeypress 某个键盘的键被按下或按住 1 4 3 onkeyup 某个键盘的键被松开 1 4 3 onload 某个页面或图像被完成加载 1 2 3 onmousedown 某个鼠标按键被按下 1 4 4 onmousemove 鼠标被移动 1 6 3 onmouseout 鼠标从某元素移开 1 4 4 onmouse
/
本文档为【全国计算机二级java学习资料大全】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。 本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。 网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。

历史搜索

    清空历史搜索