交通大學資訊工程學系 OOP : Programming in Java JavaBean & Other Topics 蔡文能...
-
Upload
amari-finamore -
Category
Documents
-
view
270 -
download
3
Transcript of 交通大學資訊工程學系 OOP : Programming in Java JavaBean & Other Topics 蔡文能...
交通大學資訊工程學系
OOP : Programming in Java
JavaBean & Other Topics
蔡文能交通大學資訊工程學系[email protected]
http://www.csie.nctu.edu.tw/~tsaiwn/java/
交通大學資訊工程學系 蔡文能 10-第 2頁
Java JavaBean
AgendaJava Reflection
Java BeanJava JDBCJ2MEJava cipher utility class/functionJava 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-第 3頁
Java JavaBean
Java ReflectionPackage java.lang.reflect;Java reflection make dynamic checking possibleWhat 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-第 4頁
Java JavaBean
Tips to Java ReflectionJava 寫的任何 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-第 5頁
Java JavaBean
DefinitionsTiermean 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.
Layermean 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.
DatabaseDatabase are designed to store, retrieve, and update data as quickly and
efficiently as possible.
Business LogicA workflow or procedure that defines the way a company conducts
business .
交通大學資訊工程學系 蔡文能 10-第 6頁
Java JavaBean
Source: Sun Microsystems, Inc., JDBC 3.0 Specification
2-Tier Database Access
Data Tier – Database Management Services
Client Tier – Presentation, Business Logic
交通大學資訊工程學系 蔡文能 10-第 7頁
Java JavaBean
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
交通大學資訊工程學系 蔡文能 10-第 8頁
Java JavaBean
Component N-Tier SystemsJ2EE Architecture
EnterpriseInformation
Services
EnterpriseInformation
Services
Web ContainerWeb Container
JSP
Servlet
EJB ContainerEJB Container
EJB
AppletContainer
AppletContainer
StandaloneClient
StandaloneClient
Connector
Firew
ar
e
Database ServerMachine
J2EE ServerMachineClient
Machine
Web Tier Business Tier EIS Tier
Client Tier
交通大學資訊工程學系 蔡文能 10-第 9頁
Java JavaBean
2-Tier vs 3-Tier Architecture
EE448: Server-Side Development
交通大學資訊工程學系 蔡文能 10-第 10頁
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-第 11頁
Java JavaBean 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
交通大學資訊工程學系 蔡文能 10-第 12頁
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.
資料來源 Craig W. Tataryn ,Introduction to MVC and the Jakarta Struts Framework
MVC 使得美工人員與程式人員的分工合作更為容易
交通大學資訊工程學系 蔡文能 10-第 13頁
Java JavaBeanJSP IntroductionBasic 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-第 14頁
Java JavaBeanJSP Scripting Elements
Declarations <%! 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-第 15頁
Java JavaBeanJSP Life CycleJSPs 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-第 16頁
Java JavaBeanPredefined 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
交通大學資訊工程學系 蔡文能 10-第 17頁
Java JavaBeanJSP “page” Directives
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-第 18頁
Java JavaBeanJSP “include” Directive/Tag
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-第 19頁
Java JavaBeanUsing JavaBeans with JSP
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-第 20頁
Java JavaBeanUsing 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);
交通大學資訊工程學系 蔡文能 10-第 21頁
Java JavaBeanDesign 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.
交通大學資訊工程學系 蔡文能 10-第 22頁
Java JavaBeanDesign Patterns: Model 2 (MVC)JavaBeans handle business logic (model).
JSPs get data from JavaBeans and build HTML (view).
Servlets process the request (controller).
MVC 使得美工人員與程式人員的分工合作更為容易
交通大學資訊工程學系 蔡文能 10-第 23頁
Java JavaBeanModel 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 使得美工人員與程式人員的分工合作更為容易
交通大學資訊工程學系 蔡文能 10-第 24頁
Java JavaBeanModel 2 Architecture (V)
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-第 25頁
Java JavaBeanModel 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 使得美工人員與程式人員的分工合作更為容易
交通大學資訊工程學系 蔡文能 10-第 26頁
Java JavaBeanJSP 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
交通大學資訊工程學系 蔡文能 10-第 27頁
Java JavaBeanCorrespondence between JSP and Servlet 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-第 28頁
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-第 29頁
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-第 30頁
Java JavaBean
JavaBeans vs. Class LibrariesBeans 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-第 31頁
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 toolsCan be a Graphic bean or a Non-graphic beanA 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 beansALL these without a line of code.
Microsoft Visual Control
交通大學資訊工程學系 蔡文能 10-第 32頁
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-第 33頁
Java JavaBean
Introspection (自我反省 )Defines techniques so components can expose internal structure at design time
by inspecting the .class fileAllows development tools to query a component to determine member variables, member methods, and interfaces
Standard naming conventions usedjava.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-第 34頁
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: messagepublic String getMessage( )
Public void setMessage(String s)
交通大學資訊工程學系 蔡文能 10-第 35頁
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-第 36頁
Java JavaBean
Javabean for JSPBenefits 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-第 37頁
Java JavaBean
A Bean Examplepackage ggyy; // 一定要放某 packagepublic 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-第 38頁
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-第 39頁
Java JavaBean
Visually Manipulated, Builder Tools
Property Sheet
Method Tracer
BeanBoxToolBox
交通大學資訊工程學系 蔡文能 10-第 40頁
Java JavaBean
JavaBean Characteristicsa public class with 0-argument constuctorit 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 customizedits state can be savedit can be analyzed by a builder toolJavabean for business logic process in MVC on serverjavabean on server is not visibleClient side javabean can be visible
交通大學資訊工程學系 蔡文能 10-第 41頁
Java JavaBean
The JavaBeans APIFeatures 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-第 42頁
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 containersEvent 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-第 43頁
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-第 44頁
Java JavaBean
Selecting the events
交通大學資訊工程學系 蔡文能 10-第 45頁
Java JavaBean
Attaching Events
交通大學資訊工程學系 蔡文能 10-第 46頁
Java JavaBean
Persistent StorageAll 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-第 47頁
Java JavaBean
Application Builder SupportA 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 timeUsed by tools to provide layout and customizing during designShould be separate from componentNot needed at run time
交通大學資訊工程學系 蔡文能 10-第 48頁
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-第 49頁
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 intercommunicateRequirements for a simple BeanPackaging Bean in a JAR fileAdditional Information – BeanInfoDefining property editorsDefining Bean customizersNaming Conventions
交通大學資訊工程學系 蔡文能 10-第 50頁
Java JavaBean
Bean NON Requirements
No Bean Superclass
Visible interface not required ‘Invisible’ Beans are OK (timer, random number generator,
complex calculation)
交通大學資訊工程學系 蔡文能 10-第 51頁
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-第 52頁
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-第 53頁
Java JavaBean
Design Pattern for javabeanAll beans should implement the Serializable interface so that the state can be saved and later restoredMethods must be made publicAll exposed methods should be threadsafe, possibly synchronized to prevent more than one thread from calling method at a given timePropertie X is exposed by public setX and getX methodsBoolean property may be exposed by isX method which returns a boolean valueThe bean which may trigger event must provide addEventListener and removeEventListener mehods for other bean to register with it to be notified
交通大學資訊工程學系 蔡文能 10-第 54頁
Java JavaBean
Design Pattern rulesConstructors 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)
交通大學資訊工程學系 蔡文能 10-第 55頁
Java JavaBean
BeanInfo classProvides more information using FeatureDescripter objectsSubclasses: BeanDescripter, PropertyDescripter,
IndexedPropertyDescripter, EventSetDescripter, MethodDescripter, ParameterDescripter
ICON to represent BeanCustomizer Class (wizard for set up)Property Editor referencesList of properties with descriptionsList of methods with descriptionsMethod to reset properties to defaults
交通大學資訊工程學系 蔡文能 10-第 56頁
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-第 57頁
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-第 58頁
Java JavaBean
Packaging the Bean
All java classes can be converted to a beanCreate 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-第 59頁
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-第 60頁
Java JavaBean
Installing the Bean
Beanbox: copy jar file to /jars directory within the BDK directory
Different depending on tool used
交通大學資訊工程學系 蔡文能 10-第 61頁
Java JavaBean
MyFirstBeanimport java.awt.*;
import java.io.Serializable;
public class FirstBean extends Canvas implements Serializable {
public FirstBean( ) {
setSize(50,30);
setBackground(Color.blue);
}
}
交通大學資訊工程學系 蔡文能 10-第 62頁
Java JavaBean
Prepare First Bean
Compile: javac FirstBean.java
Create a manifest file:
mani.txtName: FirstBean.class
Java-Bean: True
Create a jar file:
jar cvfm FirstBean.jar mani.txt FirstBean.class
交通大學資訊工程學系 蔡文能 10-第 63頁
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-第 64頁
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-第 65頁
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-第 66頁
Java JavaBean
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 …...
交通大學資訊工程學系 蔡文能 10-第 67頁
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-第 68頁
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-第 69頁
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 subsystemFeatures: 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-第 70頁
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-第 71頁
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-第 72頁
Java JavaBean
Components of Struts FrameworkModel 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-第 73頁
Java JavaBean
Spring FrameworkA 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-第 74頁
Java JavaBean
JavaBean in Spring Framework
Typical java bean with a unique idIn 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 timeSame as new ClassName( )
Beans are normally created by Spring as late as possible
http://www.springframework.org/
交通大學資訊工程學系 蔡文能 10-第 75頁
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-第 76頁
Java JavaBean
GNU/Linux“GNU Project” “GNU Operating System”Richard Stallman started the GNU Project at Sep. 1983GNU (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-第 77頁
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-第 78頁
Java JavaBean
Some ASF Java ToolsDerby: 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-第 79頁
Java JavaBean
Other Topics
謝謝捧場http://www.csie.nctu.edu.tw/~tsaiwn/java/
蔡文能