Presentation is loading. Please wait.

Presentation is loading. Please wait.

交通大學資訊工程學系 OOP : Programming in Java JavaBean & Other Topics 蔡文能 交通大學資訊工程學系

Similar presentations

Presentation on theme: "交通大學資訊工程學系 OOP : Programming in Java JavaBean & Other Topics 蔡文能 交通大學資訊工程學系"— Presentation transcript:


2 交通大學資訊工程學系 OOP : Programming in Java JavaBean & Other Topics 蔡文能 交通大學資訊工程學系

3 交通大學資訊工程學系 蔡文能 10- 第 2 頁 JavaJavaBean Agenda Java Reflection Java Bean Java JDBC J2ME Java cipher utility class/function Java Server side  JSP (Java Server Page)  Java Servlet  J2EE: EJB, JMS, JCA, JNDI, JTA, JAXP, JAAS, +CORBA  Tomcat: Servlet container  JBoss Application Server  Java Application Framework (e.g., Struts, Spring)

4 交通大學資訊工程學系 蔡文能 10- 第 3 頁 JavaJavaBean Java Reflection Package java.lang.reflect; Java reflection make dynamic checking possible What is Java Reflection?  顧名思義, Java reflection 就是可以自己知道自己是啥, 有如照鏡子 !  這是指 Java 程式在執行時期 (Run time).. 可以知道各變數的細節,可 以動態檢查 (Dynamic checking) 各變數與各類別的一些屬性 !  可以先用 getClass( ) 再用 Class 內的 getName( ) 取得物件所屬 class 的名 稱 ; 透過該 Class 物件, 我們可以查知該類別隸屬於那個 Package 、類別 本身究竟是 Public 還是 Private 、繼承自那一類別、實作了那些介面等。  甚至我們可以查知它究竟有哪些成員變數 ( 欄位 ) 以及哪些成員函數( 包括建構子)。  我們可以查知物件是不是 array? 若是 array 則可用 getComponentType( ) 取得其元素的 type ( 也是 Class 物件 ); 接著可用 java.lang.Class 內的 isPrimitive( ) 看看其元素是否為原始型別,若不是原始型別可再看看 該物件是否為 Array ?

5 交通大學資訊工程學系 蔡文能 10- 第 4 頁 JavaJavaBean Tips to Java Reflection Java 寫的任何 class 都是直接或間接 extends Object 所有的物件 (Object) 都可以叫用 getClass( ) 取得其類別 ; 此時取得的物件 是一個 java.lang.Class 物件 這叫 Class 的類別裡面有很多函數可以用, 例如 isArray( ), isInterface( ), isPrimitive( ), getName( ) 等等.. java.lang.reflect.Array 內也有許多好用的 static 函數, 例如 Array.getLength(array Object), get( ) 可取得 array 某元素 可用 Class.forName(“Stack”) 生出 Stack 的 Class 物件, 再用該 Class 物件.newInstance( ); 就可生出 Stack 物件 ; 此處的 “Stack” 可換成任何 class name; 就是說可以依使用者輸入動態地決定要產生何類別的物件。 java.lang.reflect.Constructor 可用來取得 Constructor 以便執行 有了 reflection, 程式碼在撰寫時就不必將行為寫死,包括要處理的類別 、要存取的成員變數、要呼叫的成員函數等,都可動態決定。

6 交通大學資訊工程學系 蔡文能 10- 第 5 頁 JavaJavaBean Definitions Tier mean a physical tier defined by a physical server, or a group of physical servers that perform the same function as each other but exist to extend capacity. Client stand alone program is one tier. Layer mean a section of the system that is contained within its own process or deployment unit. Multiple layers may co exist on one tier, but can easily be moved to another tier if some sort of remoting capabilities are used. Database Database are designed to store, retrieve, and update data as quickly and efficiently as possible. Business Logic A workflow or procedure that defines the way a company conducts business.

7 交通大學資訊工程學系 蔡文能 10- 第 6 頁 JavaJavaBean Source: Sun Microsystems, Inc., JDBC 3.0 Specification 2-Tier Database Access Data Tier – Database Management Services Client Tier – Presentation, Business Logic

8 交通大學資訊工程學系 蔡文能 10- 第 7 頁 JavaJavaBean Source: Sun Microsystems, Inc., JDBC 3.0 Specification Traditional(non-component) N-Tier Systems Client Tier – Presentation Logic Application Tier – Business Logic Data Tier – Database Management Services

9 交通大學資訊工程學系 蔡文能 10- 第 8 頁 JavaJavaBean Component N-Tier Systems J2EE Architecture Enterprise Information Services Enterprise Information Services Web Container JSP Servlet EJB Container EJB Applet Container Applet Container Standalone Client Standalone Client Connector Fireware Database Server Machine J2EE Server Machine Client Machine Web TierBusiness Tier EIS Tier Client Tier

10 交通大學資訊工程學系 蔡文能 10- 第 9 頁 JavaJavaBean 2-Tier vs 3-Tier Architecture EE448: Server-Side Development

11 交通大學資訊工程學系 蔡文能 10- 第 10 頁 JavaJavaBean J2ME Technologies  Personal Profile  Personal Basis Profile  Java Card TM Technology  Java Embedded Server TM Technology  JavaPhone TM API  Java Telematics Technology (JTT)  Java TV TM API  J2ME Wireless Toolkit  PersonalJava TM Technology  Wireless Developer web site  Connected Limited Device Configuration (CLDC)  Mobile Information Device Profile (MIDP)  Connected Device Configuration (CDC)  Foundation Profile

12 交通大學資訊工程學系 蔡文能 10- 第 11 頁 JavaJavaBean The Evolution of Server Side Web Ap Developement CGI (Common Gateway Interface) in any language Java Servlet JSP (, ASP, PHP) JSP + JavaBean (Model 1) JSP + JavaBean + XML Model 2 (MVC) Model 2X(MVC with XML techs) Application Framework

13 交通大學資訊工程學系 蔡文能 10- 第 12 頁 JavaJavaBean MVC Design Pattern The Model View Controller is a technique used to separate Business logic/state (the Model) from User Interface (the View) and program progression/flow (the Control). This pattern is very useful when it comes to modern web development:  The majority of modern, high usage websites are dynamically driven.  People well skilled at presentation (HTML writers) seldom know how to develop back-end solutions and visa versa.  Separating business rules from presentation is good no matter what environment you develop in be it web or desktop. 資料來源 Craig W. Tataryn,Introduction to MVC and the Jakarta Struts Framework MVC 使得美工人員與程式人員的分工合作更為容易

14 交通大學資訊工程學系 蔡文能 10- 第 13 頁 JavaJavaBean JSP Introduction Basic idea: Turn Code and HTML inside out  Use regular HTML for most of page  Mark servlet code with special tags  Entire JSP page gets translated into a servlet (once), and servlet is what actually gets invoked (for each request) JSP embeds Java or processing tags inside HTML. Welcome. Current time:  No more out.println(“ Hello ”);  Lets web designers focus on static HTML page design, and developers on dynamic Java content. ( 美工與程式分工 ) Automatic compilation  A compiled JSP is actually a servlet, with the same service() method and threaded behavior.

15 交通大學資訊工程學系 蔡文能 10- 第 14 頁 JavaJavaBean JSP Scripting Elements Declarations Scriptlets <% String strUserName = request.getParameter(“username”); String strPassword = request.getParameter(“password”); %> Expressions Welcome The current time is

16 交通大學資訊工程學系 蔡文能 10- 第 15 頁 JavaJavaBean JSP Life Cycle JSPs are compiled initially by the web container (Translation Phase) JSPs are then used by the container to service requests (Request Processing Phase) Client can NOT view the original JSP code.

17 交通大學資訊工程學系 蔡文能 10- 第 16 頁 JavaJavaBean Predefined JSP Objects request – HttpServletRequest  Determine request parameters from either GET/POST response – HttpServletResponse  Set response content type and cookies out – PrintWriter  Send buffered HTML output back to the browser session – HttpSession associated with the request application – ServletContext available to all servlets and JSP pages

18 交通大學資訊工程學系 蔡文能 10- 第 17 頁 JavaJavaBean JSP “ page ” Directives Importing classes (HttpServlet and I/O classes are automatically imported): Setting content type: (default) Turning sessions on/off for this page: (default)

19 交通大學資訊工程學系 蔡文能 10- 第 18 頁 JavaJavaBean JSP “ include ” Directive/Tag Directive: includes the file at page compilation time  Includes the actual file itself, before the JSP has been converted to a servlet.  Changes to an included file are not picked up by its parent page, until the parent page changes. Tag: includes the file at request time  Server runs the included page and inserts its output at request time, and does this for each request.  Requires runtime processing – slower for dynamic include files.  Changes to included files are automatically picked up at request time, even if the parent file did not change.

20 交通大學資訊工程學系 蔡文能 10- 第 19 頁 JavaJavaBean Using JavaBeans with JSP Identify the JavaBean and its scope. Read JavaBean properties, or method return values Set JavaBean properties directly Set JavaBean properties using request input parameters Populate all JavaBean properties with input parameters

21 交通大學資訊工程學系 蔡文能 10- 第 20 頁 JavaJavaBean Using JavaBeans with Servlets Create the JavaBean. Import the JavaBean so it’s visible to the servlet. import ggyy.HahaBean; Load the JavaBean and set its properties. HahaBean objAccount = new HahaBean(); objAccount.setUserName(strUserName); objAccount.setPassword(strPassword); Store the JavaBean in the request (or session) so it can be used by other web components. request.setAttribute("Account", objAccount); RequestDispatcher reqDispatcher = getServletContext().getRequestDispatcher("/Login.jsp"); reqDispatcher.forward(request, response);

22 交通大學資訊工程學系 蔡文能 10- 第 21 頁 JavaJavaBean Design Patterns: Model 1 Single Servlet or JSP page is responsible for  processing the request  performing business logic and/or database access  building HTML output Fine for simple applications, But.. Doesn't cut it for enterprise applications  Hard to scale without significant rewrite.  Hard to maintain or enhance, especially if the display or business logic changes frequently.  Hard to separate development tasks.

23 交通大學資訊工程學系 蔡文能 10- 第 22 頁 JavaJavaBean Design Patterns: Model 2 (MVC) JavaBeans handle business logic (model). JSPs get data from JavaBeans and build HTML (view). Servlets process the request (controller). MVC 使得美工人員與程式人員的分工合作更為容易

24 交通大學資訊工程學系 蔡文能 10- 第 23 頁 JavaJavaBean Model 2 Architecture (M) JavaBean (model):  Move business logic from servlet or JSP page into a JavaBean.  Create public get and set methods that correspond to each expected request parameter (e.g. getUserName() and setUserName(String UserName) ).  Create methods that handle business logic, such as querying the database to get an account balance. MVC 使得美工人員與程式人員的分工合作更為容易

25 交通大學資訊工程學系 蔡文能 10- 第 24 頁 JavaJavaBean Model 2 Architecture (V) JSP (view):  Get the JavaBean from the request.  Insert the JavaBean’s properties as dynamic values within static HTML template text. Welcome MVC 使得美工人員與程式人員的分工合作更為容易

26 交通大學資訊工程學系 蔡文能 10- 第 25 頁 JavaJavaBean Model 2 Architecture (C) Servlet (controller):  Get each request parameter.  Load the JavaBean and set its properties by calling the appropriate methods – setUserName(), set...()  Store the JavaBean as an attribute of the request. request.setAttribute("Account", objAccount);  Forward the request to a JSP page for display. RequestDispatcher reqDispatcher = getServletContext().getRequestDispatcher("/Login.jsp"); reqDispatcher.forward(request, response); MVC 使得美工人員與程式人員的分工合作更為容易

27 交通大學資訊工程學系 蔡文能 10- 第 26 頁 JavaJavaBean JSP vs. ??? Versus ASP or ColdFusion  Better language for dynamic part  Portable to multiple servers and operating systems Versus PHP  Better language for dynamic part  Better tool support Versus WebMacro or Velocity  Standard Versus pure servlets  More convenient to create HTML  Can use standard tools (e.g., HomeSite)  Divide and conquer  JSP developers still need to know servlet programming

28 交通大學資訊工程學系 蔡文能 10- 第 27 頁 JavaJavaBean Correspondence between JSP and Servlet Original JSP A Random Number Possible resulting servlet code public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setContentType("text/html"); HttpSession session = request.getSession(true); JspWriter out = response.getWriter(); out.println(" A Random Number "); out.println(Math.random( )); //... }

29 交通大學資訊工程學系 蔡文能 10- 第 28 頁 JavaJavaBean JavaBean at a glance A JavaBean is nothing more than a class that maintains some state data (called properties) and follows a certain set of coding conventions. JavaBeans can be easily added to and maintained by most of the Java GUI Development Tools along with certain Java runtime support (reflection and introspection)

30 交通大學資訊工程學系 蔡文能 10- 第 29 頁 JavaJavaBean So, What are JavaBeans ? A reusable software component written in Java that can be manipulated visually in a ‘ builder tool ’. (from JavaBean Specification) The JavaBeans API (java.beans.*) provides a framework for defining reusable, embeddable, modular software components. Builder Tools allow connection and configuration of Beans Begins ‘ Age of Component Developer ’ Bringing Engineering methods to Software Engineering (e.g. electronic components (e.g., IC), … )

31 交通大學資訊工程學系 蔡文能 10- 第 30 頁 JavaJavaBean JavaBeans vs. Class Libraries Beans are appropriate for software components that can be visually manipulated Class libraries are good for providing functionality that is useful to programmers, and doesn ’ t benefit from visual manipulation

32 交通大學資訊工程學系 蔡文能 10- 第 31 頁 JavaJavaBean JavaBeans Concepts (1/2) A component is a self-contained reusable software unit Components expose their features (public methods and events) to builder tools Can be a Graphic bean or a Non-graphic bean A builder tool maintains Beans in a palette or toolbox. You can select a bean from the toolbox, drop it in a form, and modify its appearance and behavior. Also, you can define its interaction with other beans ALL these without a line of code. Microsoft Visual Control

33 交通大學資訊工程學系 蔡文能 10- 第 32 頁 JavaJavaBean JavaBeans Concepts (2/2) A bean may or may not inherit from any other class or interface. If you wish to save and restore the state of the bean object, implement the interface. Graphical (Visible) beans must inherit from java.awt.Canvas or java.awt.Component so that they can be added to visual containers.

34 交通大學資訊工程學系 蔡文能 10- 第 33 頁 JavaJavaBean Introspection ( 自我反省 ) Defines techniques so components can expose internal structure at design time by inspecting the.class file Allows development tools to query a component to determine member variables, member methods, and interfaces Standard naming conventions used java.beans.Introspector.class  Based on java.lang.reflect.*  can be done by providing a java.beans.BeanInfo with the bean to describe the public methods and properties

35 交通大學資訊工程學系 蔡文能 10- 第 34 頁 JavaJavaBean JavaBean Naming Conventions (1/2) Beans  Class name:any name you like  Constructor: no argument or serialized template file  Packaging: jar file with Java-Bean: True Properties  getter and setter methods must follow some rules -- design patterns: getXXX( ), setXXX(newValue);  E.g., Property name: message public String getMessage( ) Public void setMessage(String s)

36 交通大學資訊工程學系 蔡文能 10- 第 35 頁 JavaJavaBean JavaBean Naming Conventions (2/2) Events  Event name: Answer Class name: AnswerEvent Listener name: AnswerListener Listener methods:  public void methodname(AnswerEvent e)  public void addAnswerListener(AnswerListener l)  public void removeAnswerListener( … l)

37 交通大學資訊工程學系 蔡文能 10- 第 36 頁 JavaJavaBean Javabean for JSP Benefits of jsp:useBean  Hides the Java syntax  Makes it easier to associate request parameters with Java objects (bean properties)  Simplifies sharing objects among multiple requests or servlets/JSPs jsp:useBean  Creates or accesses a bean jsp:getProperty  Puts bean property (i.e. getXxx call) into Servlet output jsp:setProperty  Sets bean property (i.e. passes value to setXxx) To use JavaBeans with JSP no environmental support is needed

38 交通大學資訊工程學系 蔡文能 10- 第 37 頁 JavaJavaBean A Bean Example package ggyy; // 一定要放某 package public class HahaBean { private String level = "median"; private String goodThing = "Row Beaf"; public String getLevel( ) { return(level); } public void setLevel(String newLevel) { level = newLevel; } public String getGoodThing() { return(goesWith); } public void setGoodThing(String what) { goodThing = what; } } // class

39 交通大學資訊工程學系 蔡文能 10- 第 38 頁 JavaJavaBean An Example of JSP uses the bean Baked Bean Values: application-based Sharing Bean level: Haha bean now has:

40 交通大學資訊工程學系 蔡文能 10- 第 39 頁 JavaJavaBean Visually Manipulated, Builder Tools Property Sheet Method Tracer BeanBox ToolBox

41 交通大學資訊工程學系 蔡文能 10- 第 40 頁 JavaJavaBean JavaBean Characteristics a public class with 0-argument constuctor it has properties with accessory methods  getXXX( ); // getter  setXXX(para); // setter it has events. It may register and receive events from other object and can generate event sent to other objects it can customized its state can be saved it can be analyzed by a builder tool Javabean for business logic process in MVC on server javabean on server is not visible Client side javabean can be visible

42 交通大學資訊工程學系 蔡文能 10- 第 41 頁 JavaJavaBean The JavaBeans API Features implemented as extensions to standard Java Class Library Main Component Services  GUI merging  Persistence for saving and restoring the state  Event Handling  Introspection  Application Builder Support so that you can change the Bean at design time

43 交通大學資訊工程學系 蔡文能 10- 第 42 頁 JavaJavaBean GUI merging and Event Handling User Interface Merging  Containers usually have Menus and/or toolbars  Allows components to add features to the menus and/or toolbars  Define mechanism for interface layout between components and containers Event Handling  Defines how components interact  Java AWT event model serves as basis for the event handling API ’ s  Provides a consistent way for components to interact with each other

44 交通大學資訊工程學系 蔡文能 10- 第 43 頁 JavaJavaBean Bean Events Define a new Event class which extends EventObject. XEvent Define a new interface for listeners to implement, this must be an extension of EventListener. XEventListener The Source must provide methods to allow listeners to register and unregister eg addXListener(), removeXListener(). The source must provide code to generate the event and send it to all registered listeners. fireXEvent() The listener must implement the interface to receive the event. changeX() The listener must register with the source to receive the event.

45 交通大學資訊工程學系 蔡文能 10- 第 44 頁 JavaJavaBean Selecting the events

46 交通大學資訊工程學系 蔡文能 10- 第 45 頁 JavaJavaBean Attaching Events

47 交通大學資訊工程學系 蔡文能 10- 第 46 頁 JavaJavaBean Persistent Storage All bean must support either Serialization or Externalization so that Components can be stored and retrieved Purpose:  To use existing data formats and plug into OLE or OpenDoc documents (e.g., Excel doc inside a Word doc)  To be “ trivial ” for the common case of a tiny Bean (by saving its internal state) Solutions  Serialization: provides an automatic way of storing out and restoring the internal state of a collection of Java objects  Externalization: provides a Bean with full control over the resulting data layout.

48 交通大學資訊工程學系 蔡文能 10- 第 47 頁 JavaJavaBean Application Builder Support A builder tool discover a bean ’ s features by a process known as introspection ( 自我反省 ).  Adhering to specific rules (design pattern) when naming Bean features.  Providing property, method, and event information with a related Bean Information class. Provides support for manipulating and editing components at design time Used by tools to provide layout and customizing during design Should be separate from component Not needed at run time

49 交通大學資訊工程學系 蔡文能 10- 第 48 頁 JavaJavaBean Beans Development Kit (BDK) To start the BeanBox:  run.bat (Windows)  (Unix) ToolBox contains the beans available BeanBox window is the form where you visually wire beans together. Properties sheet: displays the properties for the Bean currently selected within the BeanBox window.

50 交通大學資訊工程學系 蔡文能 10- 第 49 頁 JavaJavaBean Creating a JavaBean Properties can be customized at design-time. Customization can be done:  using property editor  using bean customizers Events are used when beans want to intercommunicate Requirements for a simple Bean Packaging Bean in a JAR file Additional Information – BeanInfo Defining property editors Defining Bean customizers Naming Conventions

51 交通大學資訊工程學系 蔡文能 10- 第 50 頁 JavaJavaBean Bean NON Requirements No Bean Superclass Visible interface not required  ‘ Invisible ’ Beans are OK (timer, random number generator, complex calculation)

52 交通大學資訊工程學系 蔡文能 10- 第 51 頁 JavaJavaBean Bean Requirements Introspection  Exports: properties, methods, events Properties  Subset of components internal state Methods  Invoked to execute component code Events (If any needed)  Notification of a change in state  User activities (typing, mouse actions, … ) Customization  Developer can change appearance Persistence  Save current state so it can be reloaded

53 交通大學資訊工程學系 蔡文能 10- 第 52 頁 JavaJavaBean JavaBean Other properties Indexed properties  Array value with get and set elements Bound properties  Triggers event when value changed Constrained properties  Triggers event when value changes and allows listeners to ‘ veto ’ the change

54 交通大學資訊工程學系 蔡文能 10- 第 53 頁 JavaJavaBean Design Pattern for javabean All beans should implement the Serializable interface so that the state can be saved and later restored Methods must be made public All exposed methods should be threadsafe, possibly synchronized to prevent more than one thread from calling method at a given time Propertie X is exposed by public setX and getX methods Boolean property may be exposed by isX method which returns a boolean value The bean which may trigger event must provide addEventListener and removeEventListener mehods for other bean to register with it to be notified

55 交通大學資訊工程學系 蔡文能 10- 第 54 頁 JavaJavaBean Design Pattern rules Constructors A bean has a no argument constructor Simple Properties public T getN() public void setN ( T value) Boolean Properties public boolean isN() public boolean getN() public void setN(boolean value) Indexed Properties public T getN(int index) public T[] getN() public void setN(int index, T value) public void setN(T[] values)

56 交通大學資訊工程學系 蔡文能 10- 第 55 頁 JavaJavaBean BeanInfo class Provides more information using FeatureDescripter objects Subclasses:  BeanDescripter, PropertyDescripter, IndexedPropertyDescripter, EventSetDescripter, MethodDescripter, ParameterDescripter ICON to represent Bean Customizer Class (wizard for set up) Property Editor references List of properties with descriptions List of methods with descriptions Method to reset properties to defaults

57 交通大學資訊工程學系 蔡文能 10- 第 56 頁 JavaJavaBean The beanbox Primary task is setting property values Property editors for common types  Set Font  Set background/foreground colors  Set numeric values  Set string values

58 交通大學資訊工程學系 蔡文能 10- 第 57 頁 JavaJavaBean Creating a Bean Usually extends Canvas (New window) Can extend Component ( ‘ lightweight ’ ) Needs constructor with no arguments paint( ) method used to display getPreferredSize( ), getMinimumSize( )  For layout manager defaults get and set methods (getter, setter) for each property

59 交通大學資訊工程學系 蔡文能 10- 第 58 頁 JavaJavaBean Packaging the Bean All java classes can be converted to a bean Create a JAR file (JavaARchive)  Patterned after tar utility in Unix  Bean is compressed and saved in the format of jar file which contains manifest file, class files, gif files, and other information customization files Create ‘ stub ’ manifest  Name: smith/proj/beans/BeanName.class  Java-Bean: True  (forward slashes even under Windows!)

60 交通大學資訊工程學系 蔡文能 10- 第 59 頁 JavaJavaBean Compile and make jar file Javac -d. Edit a manifest file called manifest.tmp Name: SimpleBean.class Java-Bean: True jar cfm..\jars\simplebean.jar manifest.tmp simplebean\*.class

61 交通大學資訊工程學系 蔡文能 10- 第 60 頁 JavaJavaBean Installing the Bean Beanbox: copy jar file to /jars directory within the BDK directory Different depending on tool used

62 交通大學資訊工程學系 蔡文能 10- 第 61 頁 JavaJavaBean MyFirstBean import java.awt.*; import; public class FirstBean extends Canvas implements Serializable { public FirstBean( ) { setSize(50,30); setBackground(; }

63 交通大學資訊工程學系 蔡文能 10- 第 62 頁 JavaJavaBean Prepare First Bean Compile: javac Create a manifest file: mani.txt Name: FirstBean.class Java-Bean: True Create a jar file: jar cvfm FirstBean.jar mani.txt FirstBean.class

64 交通大學資訊工程學系 蔡文能 10- 第 63 頁 JavaJavaBean Using Beans in an application Use Beans.instantiate Frame f; f = new Frame("Testing Beans"); try { ClassLoader cl = this.getClass( ).getClassLoader( ); fb =(FirstBean)Beans.instantiate(cl,"FirstBean"); } catch(Exception e) { e.printStackTrace( ); } f.add(fb);

65 交通大學資訊工程學系 蔡文能 10- 第 64 頁 JavaJavaBean Events and BeanInfo interface Question: how does a Bean exposes its features in a property sheet? Answer: using java.beans.Introspector class (which uses Core Reflection API) The discovery process is named “ introspection ” OR you can associate a class that implements the BeanInfo with your bean Implementing the BeanInfo interface allows you to explicitly publish the events a Bean fires

66 交通大學資訊工程學系 蔡文能 10- 第 65 頁 JavaJavaBean Events “ Introspection ” For a bean to be the source of an event, it must implement methods that add and remove listener objects for the type of the event:  public void add ( elt);  same thing for remove These methods help a source Bean know where to fire events. Source Bean fires events at the listeners using method of those interfaces.  Example: if a source Bean register ActionListsener objects, it will fire events at those objects by calling the actionPerformed method on those listeners

67 交通大學資訊工程學系 蔡文能 10- 第 66 頁 JavaJavaBean JavaBeans and Threads Assume your beans will be running in a multi- threaded environment It is your responsibility (the developer) to make sure that their beans behave properly under multi- threaded access For simple beans, this can be handled by simply making all methods …...

68 交通大學資訊工程學系 蔡文能 10- 第 67 頁 JavaJavaBean JavaBeans Tools BDK - Sun NetBeans – Jbuilder - Inprise Super Mojo - Penumbra Software Visual Age for Java (Eclipse) – IBM Visual Cafe - Symantec Corporation JDeveloper Suite - Oracle

69 交通大學資訊工程學系 蔡文能 10- 第 68 頁 JavaJavaBean Extend your JDK and JRE 把 所有 class 都壓縮到一個.jar 檔案 ( 名稱隨意, 但不要與現有的重複 ) 例如 : jar cvf myutilabc.jar M*.class So*.class ( 也可用 WINZIP 壓成 ZIP 檔再 rename 成.jar 檔 ) 把壓好的.jar 檔 copy 到 你 JDK 根目錄下的 \jre\lib\ext\ 即可  注意.jar 檔中的目錄樹要與各 class 宣告的 package 相符合  就是說不可以欺騙 Java compiler 與 Interpreter (JVM)  可用 jar tvf your.jar 看看 ( 或用 WINZIP 看 )  打 jar 看看 help 這樣 javac 編譯 或 java MyClass 執行 就都不用指定 classpath  若不是放 JDK 的 \jre\lib\ext\ 中, 則要指定.jar 檔為你的 classpath javac -classpath./mydir/myutil.jar; java -classpath./mydir/myutil.jar; MyTest ( 注意 分號不能省 ; 可以多個 jar 檔用 ; 分開, 也可為目錄 )

70 交通大學資訊工程學系 蔡文能 10- 第 69 頁 JavaJavaBean What ’ s in a Framework? A framework is a defined support structure in which other software applications can be organized and developed. A software framework is a reusable design and building blocks for a software system and/or subsystem Features:  Knowledge base Product reviews, configuration information, lessons learned  Document templates Requirements, Use Cases, Design Specs, Test Plans, etc.  Design patterns, standards Coding & naming standards, proven design strategies, etc.  Code libraries Base classes, format utilities, tag libraries, etc.  Code templates and generators Automated generation of starting code, based on templates

71 交通大學資訊工程學系 蔡文能 10- 第 70 頁 JavaJavaBean WAF -- Web Application Framework A Web Application Framework (WAF) is a reusable, skeletal, semi-complete modular platform that can be specialized to produce custom web applications, which commonly serve the web browsers via the Http's protocol. WAF usually implements the Model-View-Controller (MVC) design pattern, typically in the Model 2 architecture to develop request-response web-based applications on the Java EE and.Net models

72 交通大學資訊工程學系 蔡文能 10- 第 71 頁 JavaJavaBean The Struts Framework Struts is an open source MVC framework developed by the Apache Jakarta project group. Struts allows JSP/Servlet writers the ability to fashion their web applications using the MVC design pattern. By designing your web application using Struts you allow:  Architect the ability to design using the MVC pattern  Developer to exploit the Struts framework when building the app.  Web designer can learn how to program in MVC. Struts takes much difficult work out of developing an MVC based web app. The Struts framework provides a collection of canned objects which can facilitate fundamental aspects of MVC, while allowing you to extend further as need suites

73 交通大學資訊工程學系 蔡文能 10- 第 72 頁 JavaJavaBean Components of Struts Framework Model  Business Logic Bean(or session bean) 、 StateBean(or entity bean) 、 ActionForm 。 (see EJB) View  A Set of Tag library.  Language Resource File Controller  ActionServlet( controlled by struct-configs.xml)  ActionClasses Utility Classes

74 交通大學資訊工程學系 蔡文能 10- 第 73 頁 JavaJavaBean Spring Framework A popular and stable Java application framework for enterprise developmentapplication framework  Ubiquitous for Java development  Well established in enterprise Java apps  Time tested and proven reliable A primary purpose is to reduce dependencies and even introduce negative dependencies  Different from almost every other framework out there  Part of the reason it has been adopted so quickly Spring code base is proven to be well structured  Considered an alternative / replacement for the Enterprise JavaBean (EJB) model  Not exclusive to Java (e.g..NET)

75 交通大學資訊工程學系 蔡文能 10- 第 74 頁 JavaJavaBean JavaBean in Spring Framework Typical java bean with a unique id In spring there are basically two types  Singleton One instance of the bean created and referenced each time it is requested  Prototype (non-singleton) New bean created each time Same as new ClassName( ) Beans are normally created by Spring as late as possible

76 交通大學資訊工程學系 蔡文能 10- 第 75 頁 JavaJavaBean Facebook adopts LAMP architecture LAMP stands for Linux-Apache-MySQL-PHP. Instead of PHP, Perl and Python are also used. This is a free and lightweight alternative to “WISA,” Windows-IIS-SQL Server-ASP (and now, ASP.Net). These are ALL free.  Richard Stallman started the GNU Project and spearheaded the free software movement.  Richard Stallman says “free” represents end users’ liberties, not the price of software. GPL (GNU Public License) requires improved programs to also remain free. ( © CopyLeft )

77 交通大學資訊工程學系 蔡文能 10- 第 76 頁 JavaJavaBean GNU/Linux “GNU Project”  “GNU Operating System” Richard Stallman started the GNU Project at Sep. 1983 GNU (GNU’s Not Unix) was to replace UNIX. Microkernel vs. Monolithic kernel.  Mach microkernel was to complete the GNU OS.  In 1992 Andrew Tanenbaum said “Linux is Obsolete” because Linux has a monolithic kernel.  Microkernel is more secure, not as efficient.  Today, monolithic kernels are still going strong. Linux could not have happened without GNU. Stallman requested that “GNU/Linux” be used. Richard Stallman != William Richard Stevens

78 交通大學資訊工程學系 蔡文能 10- 第 77 頁 JavaJavaBean Apache HTTP Server Apache has been the most popular web server since April 1996 when it passed NCSA. Apache Software Foundation (ASF) is a non-profit organization that develops several high-quality open-source programs. Jakarta project by ASF has a number of high-quality Java web development tools:  In April 1996, Apache stood at 29% (and IIS at 1.6%) of the web server market:  In May 2010, Apache stands at 55% (and IIS at 25%): 

79 交通大學資訊工程學系 蔡文能 10- 第 78 頁 JavaJavaBean Some ASF Java Tools Derby: Java database (originally IBM Cloudscape; now also called Sun Java DB)‏ Tomcat: Servlet and JavaServer Pages (JSP) Server. Ant: Portable build tool (java “make”)‏ Struts: Web application framework for input validation and flow control (page-to-page). Lucene: Text indexing/search ASF stands for Apache Software Foundation (ASF) See

80 交通大學資訊工程學系 蔡文能 10- 第 79 頁 JavaJavaBean Other Topics 謝謝捧場 蔡文能

Download ppt "交通大學資訊工程學系 OOP : Programming in Java JavaBean & Other Topics 蔡文能 交通大學資訊工程學系"

Similar presentations

Ads by Google