• 1. J2EE技术平台胡晓军
  • 2. 2JDBC提供访问关系型数据库的标准Java API 使用SQL 对于Java编程API的实现由各厂商实现,针对不同数据库编写不同的驱动程序。
  • 3. 3JDBC 的目标SQL-Level 100% 纯Java 简单 高效 利用现有的数据库技术 提供多种方法简化不同功能需求的代码
  • 4. 4JDBC 体系架构ApplicationJDBCDriverJava 代码调用JDBC库 JDBC装载驱动 驱动与特定数据库连接 可以使用多个驱动,也可以使用多个数据库 可以在不修改程序代码的情况下更换要使用的数据库
  • 5. 5JDBC DriversType I: “Bridge” Type II: “Native” Type III: “Middleware” Type IV: “Pure”
  • 6. 6JDBC APIJDBC 的实现类在java.sql包中,需要在程序中通过import语句引入
  • 7. 7DriverManagerDriverManager 试用各种驱动 使用第一个可以正确使用的驱动 一个驱动类装载时,自动在DriverManager中注册 Class.forName(“org.gjt.mm.mysql.Driver”); Connection c = DriverManager.getConnection(...);
  • 8. 8JDBC对象类DriverManager 装载、选择驱动 Driver 连接实际数据库 Connection 连接数据库的对象 Statement 执行独立的SQL语句 ResultSet Statement返回的结果集
  • 9. 9JDBC 类的使用DriverManagerDriverConnectionStatementResultSet
  • 10. JDBC类图
  • 11. 11JDBC URLjdbc:subprotocol:source 不同的驱动有不同的URL写法 jdbc:odbc:DataSource 例如jdbc:odbc:Northwind jdbc:mysql://host[:port]/database 例如jdbc:mysql://localhost/accounting
  • 12. 12DriverManagerConnection getConnection (String url, String user, String password) 与给定的JDBC URL连接,并使用user和password参数 可能产生java.sql.SQLException 返回一个 Connection对象
  • 13. 13ConnectionConnection对象表示和一个特定数据的连接会话 SQL语句在Connection环境里执行并得到返回结果 可以创建到一个数据库的多个Connection连接 在Connection中有一些方法能够得到数据库的metadata信息,如数据库中表结构和字段属性 在Connection还有保证数据库事务的方法
  • 14. 14获得一个 ConnectionString url = “jdbc:mysql://localhost/test"; try { Class.forName (" org.gjt.mm.mysql.Driver "); Connection con = DriverManager.getConnection(url,”root”,”root”); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }
  • 15. 15StatementStatement对象用来执行SQL命令并获取相应的结果 Statement对象的主要方法 ResultSet executeQuery(String) Execute a SQL statement that returns a single ResultSet. int executeUpdate(String) Execute a SQL INSERT, UPDATE or DELETE statement. Returns the number of rows changed. boolean execute(String) Execute a SQL statement that may return multiple results.
  • 16. 16ResultSetResultSet用来访问Statement对象执行后得到的数据结果集 每个Statement每次只能打开一个ResultSet 数据库表中的记录按顺序获取 ResultSet对象维护一个指向当前记录的游标 Next方法把游标指向下一个记录 新的JDBC中允许游标指向上一个记录,有部分支持高版本JDBC规范的驱动程序可以支持这个功能
  • 17. Naming and Directory servicesNaming services bind a name with an object A set of name-to-object bindings is called a Context Retrieving an object based on its name is called lookup Directory Services extend naming services Directory services allow named objects to have attributes that provide additional information about them Allow one among several objects to be located Provide operations for creating, adding, removing, and modifying the attributes associated with objects in a directory
  • 18. JNDIJNDI allows accessing different naming and directory services uniformly Active Directory Services Novell Directory Services Network Information Services Objects within a J2EE application Why? Different services use different naming services JNDI provides a uniform way to access it A J2EE application can navigate across files, directories, databases, objects and networks seamlessly
  • 19. How is naming managed in JNDI?com.infy.cache.CacheManager com.infy.cache.SessionManager TellerHome AccountHome Analogous to files and folders in a file system Objects bound are serialized onto the JNDI tree When object is looked up, it is de-serialized
  • 20. Binding an object in JNDItry { CacheManager theObject = new CacheManager (); //Get the Initial Context Context ctx = new InitialContext(); //Create required sub-context ctx.createSubContext ("com"); ctx.createSubContext ("com.infy"); ctx.createSubContext ("com.infy.cache"); //Bind the object in JNDI ctx.bind ("com.infy.cache.CacheManager", theObject); } catch (NamingException ne) { System.out.println ("Naming Exception: " + ne.getMessage()); ne.printStrackTrace(); } catch (Exception e) { System.out.println ("Error binding object in JNDI "+ e.getMessage()); e.printStackTrace(); }
  • 21. Looking up an object in JNDI treetry { //Get the Initial Context Context ctx = new InitialContext(); //Lookup the object by name! Object obj = ctx.lookup (“com.infy.cache.CacheManager”); //Before using the object, narrow it to the actual class CacheManager theObject = ctx.narrow (obj, CacheManager.class); // Narrow successful! Now you can invoke methods on the object! ... } catch (NamingException ne) { System.out.println ("Naming Exception: " + ne.getMessage()); ne.printStrackTrace(); } catch (Exception e) { System.out.println ("Error retrieving object "+ e.getMessage()); e.printStackTrace(); }
  • 22. Environment variables to be passed to get Initial context in clientEnvironment VariableEquivalent Constant in CodeWhat it configures?java.naming.factory.initialContext.INITIAL_CONTEXT_FACTORYClass name of the context factory to use. This is the class name given by the service providerjava.naming.provider.urlContext.PROVIDER_URLConfiguration information for service provider to use. (The Server)java.naming.security.principalContext.SECURITY_PRINCIPALIdentity of the principal (user) who wants to use the service providerjava.naming.security.credentialsContext.SECURITY_CREDENTIALSPassword for the principal
  • 23. Important APIs in J2EE - JNDIConstructors in ‘javax.naming.InitialContext’ class (implements Context interface) Commonly used methods in javax.naming.Context interface InitialContext (); – Called in Server side code InitialContext (Hashtable configuration); - **Usually called in client side code InitialContext (Properties configuration); - **Usually Called in client side code * Initial context is got using the environment variables passed. Env variables required to establish connection to remote server. (Example: One J2EE server communicating with another J2EE Server)// Lookup an object in JNDI Tree Object lookup(String name); // List all objects in a context NamingEnumeration list (String subcontextName); NamingEnumeration list (String subcontextName); // Binding an object in JNDI tree void bind (String name, Object object); void rebind (String name, Object object); // Remove an object from context void unbind (String name);// Create a subcontext Context createSubcontext (String name); // Delete a subcontext void destroySubcontext (String name);
  • 24. Synchronous vs Asynchronous communication
  • 25. JMSMany enterprise applications may require asynchronous messaging JMS provides a means for asynchronous messaging A component sends a message to a destination the recipient will retrieve the message from the destination But, for the communication to take place, the sender and the receiver need not be available at the same time Messaging enables distributed communication that is loosely coupled The sender need not know anything about the receiver and the receiver need not know anything about the sender Both the sender and the receiver should know only the message format and the destination
  • 26. JMSJava Message Service or JMS is a Java API that allows applications to create, send, receive and read messages A messaging service that implements JMS is a JMS provider The JMS API makes JMS applications portable across various JMS providers Messaging Systems can be divided into two domains Point-to-Point Publish/Subscribe
  • 27. Point to PointBased on queues The producer creates the message, leaves it in the queue and the consumer consumes the message from the queue Each message has a single consumer Consumer must acknowledge receipt of the message so that the message is removed from the queue
  • 28. Point to PointPoint-to-Point
  • 29. Publish/SubscribeCan have multiple recipients per message Producers publish their messages in topics Consumers should subscribe to a topic Messages in the topics subscribed by consumers will be delivered to those consumers
  • 30. Publish/SubscribePublish/Subscribe
  • 31. 31对Web Service的支持早期的J2EE标准未包括对XML Web Service的支持 各个厂商提供自己的方案 支持UDDI/WSDL/SOAP WSI组织保证互操作性 SUN的方案 JAXP/JAXB/JAXM/JAXR/JWSDL JAX/RPC JAX* – Java API for XML *
  • 32. 32What is a Web Service?A modular, well-defined, encapsulated function Used for loosely coupled integration between applications or systems Based on XML, transported in two forms: Synchronous (RPC): SOAP Asynchronous (messaging): SOAP and ebXML Messaging Sometimes advertised and discovered in a service registry UDDI, ebXML Reg/Rep, and WSDL are popular standards Over Intranet and Internet
  • 33. Example ScenarioBook StoreHarry Potter (5) Price: 25.95 Copies in Stock: 1Harry Potter (5) Price: 25.95 Copies in Stock: 0Book StoreHarry Potter (5) Price: 20.95 Copies in Stock: 5Buy Harry Potter (5)Buy Harry Potter (5)How Much?20.95Buy itHarry Potter (5) Price: 20.95 Copies in Stock: 4Harry Potter (5) Price: 25.95 Copies in Stock: 1Harry Potter (5) Price: 25.95 Copies in Stock: 0
  • 34. 34Web Application vs. Web Services
  • 35. 35Characteristics of Web ServicesXML based Message-based Programming language independent Dynamically located Accessed over the internet Loosely coupled Based on industry standards
  • 36. 36Web Services Model Over J2EE
  • 37. SOAP Intuition
  • 38. POST /Temperature HTTP/1.1 Host: www.weather.com Content-Type: text/xml Content-Length: SOAPMethodName: #CurrentTemp 37919 URI- Uniform Resource Identifier some-URI -> www.netsolve.com or www.globus.com Http HeaderXml PayloadSoap ExtensionsSOAP Request Example
  • 39. HTTP/1.1 200 OK Content-Type: text/xml Content-Length: 5 42 Http HeaderXml PayloadSOAP Response Example
  • 40. J2EE多层系统主要由架构设计、框架以及多个设计模式组成。 设计模式是一种实践的总结,是OOP最直接的表现。 掌握设计模式与否是衡量程序员设计水平高低的主要依据。设计模式是系统架构之基础
  • 41. GoF设计模式主要列举了常用的23种模式 Java的GoF设计模式实现主要表现在面向接口编程。 工厂模式是最常用的一种设计模式GoF设计模式
  • 42. 工厂模式简介设定一个Class名称是AClass,在面向对象编程中,一般一个Class都会继承一个接口,设定AClass的接口为AInterface,那么生成AClass的对象方法如下: AInterface a = new AClass();
  • 43. 工厂模式简介(续)改写成下列方式: AInterface a = Afactory.create(); //代码2 上面代码2这一行是使用Afactory的create方法来生成AInterface实例
  • 44. 工厂模式简介(续)Afactory的create方法封装了具体创建细节。 解耦了创建过程和使用过程,系统可扩展性增强,稳定性增强。 Afactory的create方法代码: public static AInterface create(){ …… return new AClass(); }
  • 45. EJB调用是工厂模式的实现调用EJB 语法: EJBHome em = JNDIServer.getRemoteHome(EJB-JNDI-NAME); EJBObject myEJB = em.create(); em.create()类似Afactory.create(); EJBObject 是接口
  • 46. 会话 Bean和实体Bean一个会话Bean中调用多个实体Bean 该会话Bean是一个Façade类/Manager类 使用Façade 会话Bean优点: 1. 提供性能,节省客户端直接调用实体Bean的网络开销 2. 解耦分层,利于扩展变化。
  • 47. DTO模式DTO模式或称VO模式,是指将数据封装成普通的JavaBeans,在J2EE多个层次之间传输。 DTO类似信使,是同步系统中的Message 该JavaBeans可以是一个数据模型Model
  • 48. 数据建模Model 、 Domain Object以及DTO关系 1. 分析提炼Model是系统设计之起端 2. 系统设计之初,三者基本统一 3. 系统复杂化后,DTO可能是多个Model组合实现;
  • 49. MVC模式MVC模式是J2EE Web层的主要实现
  • 50. Struts框架(Framework)Struts框架是MVC模式的实现(特例化) 框架(Framework)与模式(Pattern)的关系: 1. 设计模式比框架更抽象; 2. 设计模式是比框架更小的体系元素; 3. 框架比设计模式更加特例化;
  • 51. 代理模式代理模式是容器级别或框架级别的模式 代理模式可以强迫客户端对一个对象的方法调用间接通过代理类进行。 通常代理模式有以下几种:访问代理(Access Proxy)、虚拟代理和远程代理等。
  • 52. 代理模式接口: public interface BaseIF{ public Object myMethod(); } 原始类: public class OriginClass implements BaseIF{ public Object myMethod (){ return " hello , It is me! "; } }
  • 53. 代理模式(续)代理类: public class ProxyClass implements BaseIF{ public Object myMethod (){ //通过网络协议调用远程的OriginClass BaseIF instance = getRemoteOrigin (); Return instance.myMethod (); } ….. } 客户端调用 BaseIF instance = new Proxy Class(); String result = (String)instance.myMethod (); System.out.println(result); //将会输出 hello , It is me!
  • 54. 动态代理模式动态代理利用Java的反射(Reflect)机制,可以在运行时刻将一个对象实例的方法调用分派到另外一个对象实例的调用。 动态代理模式可以在运行时刻创建继承某个接口的类型安全的代理对象,而无需在代码编译时编译这些代理类代码。是AOP的良好实现。 使用动态代理模式,基本可以实现完全解耦,例如JBoss 3.XX容器核心。
  • 55. SpringIoC/DI AOP