Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
OOP : Programming in Java JavaBean & Other Topics 蔡文能 交通大學資訊工程學系 [email protected] http://www.csie.nctu.edu.tw/~tsaiwn/java/ 交通大學資訊工程學系 Java JavaBean 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) 交通大學資訊工程學系 蔡文能 10-第2頁 Java JavaBean 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 ? 交通大學資訊工程學系 蔡文能 10-第3頁 Java JavaBean 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, 程式碼在撰寫時就不必將行為寫死,包括要處理的類別 、要存取的成員變數、要呼叫的成員函數等,都可動態決定。 交通大學資訊工程學系 蔡文能 10-第4頁 Java JavaBean 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 . 交通大學資訊工程學系 蔡文能 10-第5頁 Java JavaBean 2-Tier Database Access Client Tier – Presentation, Business Logic Data Tier – Database Management Services Source: Sun Microsystems, Inc., JDBC 3.0 Specification 交通大學資訊工程學系 蔡文能 10-第6頁 Java JavaBean Traditional(non-component) N-Tier Systems Client Tier – Presentation Logic Application Tier – Business Logic Data Tier – Database Management Services 交通大學資訊工程學系 蔡文能 Source: Sun Microsystems, Inc., JDBC 3.0 Specification 10-第7頁 Java JavaBean Component N-Tier Systems J2EE Architecture Client Tier Fireware Applet Container Web Tier Web Container Connector EJB Container JSP Standalone Client Client Machine EIS Tier Business Tier Enterprise Information Services EJB Servlet J2EE Server Machine Database Server Machine 交通大學資訊工程學系 蔡文能 10-第8頁 EE448: Server-Side Development Java JavaBean 2-Tier vs 3-Tier Architecture 交通大學資訊工程學系 蔡文能 10-第9頁 Java JavaBean J2ME Technologies Personal Profile Personal Basis Profile Java CardTM Technology Java Embedded ServerTM Technology JavaPhoneTM API Java Telematics Technology (JTT) Java TVTM API J2ME Wireless Toolkit PersonalJavaTM Technology Wireless Developer web site Connected Limited Device Configuration (CLDC) Mobile Information Device Profile (MIDP) Connected Device Configuration (CDC) Foundation Profile 交通大學資訊工程學系 蔡文能 10-第10頁 JavaBean The Evolution of Server Side Web Ap Developement Java 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 交通大學資訊工程學系 蔡文能 10-第11頁 Java JavaBean 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. MVC 使得美工人員與程式人員的分工合作更為容易 資料來源 Craig W. Tataryn ,Introduction to MVC and the Jakarta Struts Framework 交通大學資訊工程學系 蔡文能 10-第12頁 Java JSP Introduction JavaBean 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. <HTML> <BODY> <H2>Welcome <%= request.getParameter("username") %>.</H2> <P>Current time: <%= new java.util.Date() %></P> </BODY> </HTML> No more out.println(“<html><b>Hello</b></html>”); 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. 交通大學資訊工程學系 蔡文能 10-第13頁 JSP Scripting Elements Java Declarations JavaBean <%! variables or methods %> <%! private int m_iAccessCount = 0; %> Scriptlets <% Java code %> <% String strUserName = request.getParameter(“username”); String strPassword = request.getParameter(“password”); %> Expressions <%= Java expressions %> <p>Welcome <%= strUserName %> </p> <p>The current time is <%= new java.util.Date() %> </p> 交通大學資訊工程學系 蔡文能 10-第14頁 Java JSP Life Cycle JavaBean 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. 交通大學資訊工程學系 蔡文能 10-第15頁 Java Predefined JSP Objects JavaBean 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 交通大學資訊工程學系 蔡文能 10-第16頁 Java JSP “page” Directives JavaBean Importing classes (HttpServlet and I/O classes are automatically imported): <%@ page import="javax.xml.*,com.mypackage.*" %> Setting content type: <%@ page contentType="text/html" %> (default) <%@ page contentType="text/xml" %> Turning sessions on/off for this page: <%@ page session="true" %> (default) <%@ page session= "false" %> 交通大學資訊工程學系 蔡文能 10-第17頁 Java JSP “include” Directive/Tag JavaBean Directive: includes the file at page compilation time <%@ include file="Toolbar.jsp" %> 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 <jsp:include page="footer.html" /> 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. 交通大學資訊工程學系 蔡文能 10-第18頁 Java Using JavaBeans with JSP JavaBean Identify the JavaBean and its scope. <jsp:useBean id="Account" class="cis.AccountBean" scope="request" /> Read JavaBean properties, or method return values <jsp:getProperty name="Account" property="userName" /> Set JavaBean properties directly <jsp:setProperty name="Account" property="userName" value="Greg" /> Set JavaBean properties using request input parameters <jsp:setProperty name="Account" property="userName" /> Populate all JavaBean properties with input parameters <jsp:setProperty name="Account" property="*" /> 交通大學資訊工程學系 蔡文能 10-第19頁 Java Using JavaBeans with Servlets JavaBean 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); 交通大學資訊工程學系 蔡文能 10-第20頁 Java Design Patterns: Model 1 JavaBean 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. 交通大學資訊工程學系 蔡文能 10-第21頁 Java Design Patterns: Model 2 (MVC) JavaBean JavaBeans handle business logic (model). JSPs get data from JavaBeans and build HTML (view). Servlets process the request (controller). MVC 使得美工人員與程式人員的分工合作更為容易 交通大學資訊工程學系 蔡文能 10-第22頁 Java Model 2 Architecture (M) JavaBean 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 使得美工人員與程式人員的分工合作更為容易 交通大學資訊工程學系 蔡文能 10-第23頁 Java Model 2 Architecture (V) JavaBean JSP (view): Get the JavaBean from the request. <jsp:useBean id=“Account” scope=“request” class=“cis.AccountBean”/> Insert the JavaBean’s properties as dynamic values within static HTML template text. <H2>Welcome <jsp:getProperty name=“Account” property=“userName”/> </H2> MVC 使得美工人員與程式人員的分工合作更為容易 交通大學資訊工程學系 蔡文能 10-第24頁 Java Model 2 Architecture (C) JavaBean 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 使得美工人員與程式人員的分工合作更為容易 交通大學資訊工程學系 蔡文能 10-第25頁 JSP vs. ??? Java JavaBean 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 交通大學資訊工程學系 蔡文能 10-第26頁 Correspondence between JSP and Servlet Java JavaBean Original JSP <H1>A Random Number</H1> <%= Math.random( ) %> 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("<H1>A Random Number</H1>"); out.println(Math.random( )); //... } 交通大學資訊工程學系 蔡文能 10-第27頁 Java JavaBean 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) 交通大學資訊工程學系 蔡文能 10-第28頁 Java JavaBean 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), …) 交通大學資訊工程學系 蔡文能 10-第29頁 Java JavaBean 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 交通大學資訊工程學系 蔡文能 10-第30頁 Java JavaBean 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 交通大學資訊工程學系 蔡文能 10-第31頁 Java JavaBean 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 java.io.Serializable interface. Graphical (Visible) beans must inherit from java.awt.Canvas or java.awt.Component so that they can be added to visual containers. 交通大學資訊工程學系 蔡文能 10-第32頁 Java JavaBean 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 交通大學資訊工程學系 蔡文能 10-第33頁 Java JavaBean 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) 交通大學資訊工程學系 蔡文能 10-第34頁 Java JavaBean 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) 交通大學資訊工程學系 蔡文能 10-第35頁 Java JavaBean 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 交通大學資訊工程學系 蔡文能 10-第36頁 Java JavaBean 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 交通大學資訊工程學系 蔡文能 10-第37頁 Java JavaBean An Example of JSP uses the bean <BODY> <H1>Baked Bean Values: application-based Sharing</H1> <jsp:useBean id="applicationBean" class="ggyy.HahaBean" scope="application" /> <jsp:setProperty name="applicationBean" property="*" /> <H2>Bean level: <jsp:getProperty name="applicationBean" property="level" /> </H2> <H2>Haha bean now has: <jsp:getProperty name="applicationBean" property="goodThing"/> </H2></BODY></HTML> 交通大學資訊工程學系 蔡文能 10-第38頁 Java JavaBean Visually Manipulated, Builder Tools ToolBox BeanBox Property Sheet Method Tracer 交通大學資訊工程學系 蔡文能 10-第39頁 Java JavaBean 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 交通大學資訊工程學系 蔡文能 10-第40頁 Java JavaBean 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 交通大學資訊工程學系 蔡文能 10-第41頁 Java JavaBean 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 交通大學資訊工程學系 蔡文能 10-第42頁 Java JavaBean 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. 交通大學資訊工程學系 蔡文能 10-第43頁 Java JavaBean Selecting the events 交通大學資訊工程學系 蔡文能 10-第44頁 Java JavaBean Attaching Events 交通大學資訊工程學系 蔡文能 10-第45頁 Java JavaBean 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. 交通大學資訊工程學系 蔡文能 10-第46頁 Java JavaBean 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 交通大學資訊工程學系 蔡文能 10-第47頁 Java JavaBean Beans Development Kit (BDK) To start the BeanBox: run.bat (Windows) run.sh (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. 交通大學資訊工程學系 蔡文能 10-第48頁 Java JavaBean 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 交通大學資訊工程學系 蔡文能 10-第49頁 Java JavaBean Bean NON Requirements No Bean Superclass Visible interface not required ‘Invisible’ Beans are OK (timer, random number generator, complex calculation) 交通大學資訊工程學系 蔡文能 10-第50頁 Java JavaBean 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 交通大學資訊工程學系 蔡文能 10-第51頁 Java JavaBean 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 交通大學資訊工程學系 蔡文能 10-第52頁 Java JavaBean 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 交通大學資訊工程學系 蔡文能 10-第53頁 Java JavaBean 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 public public value) public 交通大學資訊工程學系 蔡文能 T getN(int index) T[] getN() void setN(int index, T void setN(T[] values) 10-第54頁 Java JavaBean 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 交通大學資訊工程學系 蔡文能 10-第55頁 Java JavaBean 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 交通大學資訊工程學系 蔡文能 10-第56頁 Java JavaBean 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 交通大學資訊工程學系 蔡文能 10-第57頁 Java JavaBean 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!) 交通大學資訊工程學系 蔡文能 10-第58頁 Java JavaBean Compile and make jar file Javac -d . SimpleBean.java Edit a manifest file called manifest.tmp Name: SimpleBean.class Java-Bean: True jar cfm ..\jars\simplebean.jar manifest.tmp simplebean\*.class 交通大學資訊工程學系 蔡文能 10-第59頁 Java JavaBean Installing the Bean Beanbox: copy jar file to /jars directory within the BDK directory Different depending on tool used 交通大學資訊工程學系 蔡文能 10-第60頁 Java JavaBean MyFirstBean import java.awt.*; import java.io.Serializable; public class FirstBean extends Canvas implements Serializable { public FirstBean( ) { setSize(50,30); setBackground(Color.blue); } } 交通大學資訊工程學系 蔡文能 10-第61頁 Java JavaBean Prepare First Bean Compile: javac FirstBean.java Create a manifest file: mani.txt Name: FirstBean.class Java-Bean: True Create a jar file: jar cvfm FirstBean.jar mani.txt FirstBean.class 交通大學資訊工程學系 蔡文能 10-第62頁 Java JavaBean 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); 交通大學資訊工程學系 蔡文能 10-第63頁 Java JavaBean 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 交通大學資訊工程學系 蔡文能 10-第64頁 Java JavaBean 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<EventListenerType>(<EventListenerType> 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 交通大學資訊工程學系 蔡文能 10-第65頁 Java JavaBean JavaBeans and Threads Assume your beans will be running in a multithreaded environment It is your responsibility (the developer) to make sure that their beans behave properly under multithreaded access For simple beans, this can be handled by simply making all methods …... 交通大學資訊工程學系 蔡文能 10-第66頁 Java JavaBean JavaBeans Tools BDK - Sun NetBeans – www.netbeans.org Jbuilder - Inprise Super Mojo - Penumbra Software Visual Age for Java (Eclipse) – IBM Visual Cafe - Symantec Corporation JDeveloper Suite - Oracle 交通大學資訊工程學系 蔡文能 10-第67頁 Java JavaBean 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 MyClass.java 編譯 或 java MyClass 執行就都不用指定classpath 若不是放 JDK 的 \jre\lib\ext\ 中, 則要指定 .jar 檔為你的 classpath javac -classpath ./mydir/myutil.jar; MyTest.java java -classpath ./mydir/myutil.jar; MyTest (注意 分號不能省; 可以多個 jar 檔用 ; 分開, 也可為目錄) 交通大學資訊工程學系 蔡文能 10-第68頁 Java JavaBean 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 交通大學資訊工程學系 蔡文能 10-第69頁 Java JavaBean 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 交通大學資訊工程學系 蔡文能 10-第70頁 Java JavaBean 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 http://jakarta.apache.org/struts/ 交通大學資訊工程學系 蔡文能 10-第71頁 Java JavaBean 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 交通大學資訊工程學系 蔡文能 10-第72頁 Java JavaBean Spring Framework A popular and stable Java application framework for enterprise development 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) http://www.springframework.org/ 交通大學資訊工程學系 蔡文能 10-第73頁 Java JavaBean 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 http://www.springframework.org/ 交通大學資訊工程學系 蔡文能 10-第74頁 Java JavaBean 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 ) 交通大學資訊工程學系 蔡文能 10-第75頁 Java JavaBean 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 10-第76頁 Java JavaBean 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: http://jakarta.apache.org/ In April 1996, Apache stood at 29% (and IIS at 1.6%) of the web server market: http://survey.netcraft.com/Reports/9604/ALL/ In May 2010, Apache stands at 55% (and IIS at 25%): http://news.netcraft.com/archives/web_server_survey.html 交通大學資訊工程學系 蔡文能 10-第77頁 Java JavaBean 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 http://jakarta.apache.org/ 交通大學資訊工程學系 蔡文能 10-第78頁 Java JavaBean Other Topics 謝謝捧場 http://www.csie.nctu.edu.tw/~tsaiwn/java/ 蔡文能 交通大學資訊工程學系 蔡文能 10-第79頁