40
第第第第 J2EE 第第 1. Java 2 Platform Enterprise Edition (J2EE) 1.3 API 2. J2EE Architecture 3. J2EE Application Development Lifecycl e 4. JSP 5. Servlet 6. JavaBean 7. EJB

第十四章 J2EE 介绍 1.Java 2 Platform Enterprise Edition (J2EE) 1.3 API 2.J2EE Architecture 3.J2EE Application Development Lifecycle 4.JSP 5.Servlet 6.JavaBean

Embed Size (px)

Citation preview

第十四章 J2EE 介绍

1. Java 2 Platform Enterprise Edition (J2EE) 1.3 API

2. J2EE Architecture3. J2EE Application Development Lifecycle4. JSP5. Servlet6. JavaBean7. EJB

1 、 J2EE 1.3 APIs and Technologies

2 、 N-tier J2EE Architecture

2 、 Application distribute multi-tier

2 、 J2EE Containers & Components

3 、 J2EE Application Development Lifecycle

Write and compile component codeServlet, JSP, EJB

Write deployment descriptors for componentsAssemble components into ready-to-deployable packageDeploy the package on a server

4 、 JSP• JSP (Java Server Pages) is an alternate way of creating servlets

–JSP is written as ordinary HTML, with a little Java mixed in–The Java is enclosed in special tags, such as <% ... %>–The HTML is known as the template text

• JSP files must have the extension .jsp–or other client sees only the resultant HTML, as usual JSP is translated into a Java servlet, which is then compiled–Servlets are run in the usual way

JSP scripting elements

There is more than one type of JSP “tag,” depending on what you want done with the Java<%= expression %>

The expression is evaluated and the result is inserted into the HTML page

<% code %>The code is inserted into the servlet's service methodThis construction is called a scriptlet

<%! declarations %>The declarations are inserted into the servlet class, not into a method

Example JSP

<HTML><BODY>Hello!  The time is now <%= new java.util.Date() %></BODY></HTML>

Notes:

The <%= ... %> tag is used, because we are computing a value and inserting it into the HTML

The fully qualified name (java.util.Date) is used, instead of the short name (Date), because we haven’t yet talked about how to do import declarations

Example

<HTML>

<HEAD>

<TITLE>Hello World Example</TITLE>

</HEAD>

<BODY>

<H2>Hello World Example</H2>

<B>Hello <% =request.getParameter("name") %>!</B>

</BODY>

</HTML>

Page is in the proj web application: tomcat_home/webapps/proj/HelloWorld.jsp

Invoked with URL:http://<host>:<port>/proj/HelloWorld.jsp?name=snoopy

Invoked with URL (no parameter):http://<host>:<port>/proj/HelloWorld.jsp

Variables

You can declare your own variables, as usualJSP provides several predefined variables

request : The HttpServletRequest parameterresponse : The HttpServletResponse parametersession : The HttpSession associated with the request, or null if there is noneout : A JspWriter (like a PrintWriter) used to send output to the client

Example:Your hostname: <%= request.getRemoteHost() %>

What does a JSP-Enabled Server do?

receives a request for a .jsp page

parses it

converts it to a Servlet (JspPage) with your code inside the _jspService() method

runs it

Translation of JSP to Servlet

Two phases:

Page translation: JSP is translated to a Servlet. Happens the first time the JSP is accessed

Request time: When page is requested, Servlet runs

No interpretation of JSP at request time!

Design Stategy

Do not put lengthy code in JSP page

Do put lengthy code in a Java class and call it from the JSP page

Why? Easier for

Development (written separately)

Debugging (find errors when compiling)

Testing

Code Reuse

5 、 Servlet

The purpose of a servlet is to create a Web page in response to a client requestServlets are written in Java, with a little HTML mixed in

The HTML is enclosed in out.println( ) statements

A “Hello World” servletpublic class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n";out.println(docType + "<HTML>\n" + "<HEAD><TITLE>Hello</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1>Hello World</H1>\n" + "</BODY></HTML>"); }}

This is mostly Java with a little HTML mixed in

// HTTPGetServlet.java: Creating and sending a page //to the clientimport javax.servlet.*;import javax.servlet.http.*;import java.io.*;public class HTTPGetServlet extends HttpServlet { public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { PrintWriter output; response.setContentType( "text/html" ); // content type output = response.getWriter(); // get writer

// create and send HTML page to client StringBuffer buf = new StringBuffer(); buf.append( "<HTML><HEAD><TITLE>\n" ); buf.append( "A Simple Servlet Example\n" ); buf.append( "</TITLE></HEAD><BODY>\n" ); buf.append( "<H1>Welcome to Servlets!</H1>\n" ); buf.append( "</BODY></HTML>" ); output.println( buf.toString() ); output.close(); // close PrintWriter stream }}

<!-- HTTPGetServlet.html --><HTML><HEAD> <TITLE> Servlet HTTP GET Example </TITLE> </HEAD><BODY> <FORM ACTION="http://localhost:8080/ servlet/HTTPGetServlet" METHOD="GET"> <P>Click the button to have the servlet send an HTML document</P> <INPUT TYPE="submit" VALUE="Get HTML Documen

t"> </FORM> </BODY></HTML>

Relationships

In servlets: HTML code is printed from java code

In JSP pages: Java code is embedded in HTML code

Java

HTMLJava

HTML

6 、 JavaBean// LogoAnimator.java: Animation beanpackage jhtp3beans;import java.awt.*;import java.awt.event.*;import java.io.*;import java.net.*;import javax.swing.*;public class LogoAnimator extends JPanel implements ActionListener, Serializable { protected ImageIcon images[]; protected int totalImages = 30, currentImage = 0, animationDelay = 50;

protected Timer animationTimer; public LogoAnimator() { setSize( getPreferredSize() ); images = new ImageIcon[ totalImages ]; URL url; for ( int i = 0; i < images.length; ++i ) { url = getClass().getResource( "deitel" + i + ".gif" ); images[ i ] = new ImageIcon( url ); } startAnimation(); }

public void paintComponent( Graphics g ) { super.paintComponent( g ); if ( images[ currentImage ].getImageLoadStatus() ==

MediaTracker.COMPLETE ) { g.setColor( getBackground() ); g.drawRect( 0, 0, getSize().width, getSize().height ); images[ currentImage ].paintIcon( this, g, 0, 0 ); currentImage = ( currentImage + 1 ) %

totalImages; } }

public void actionPerformed( ActionEvent e ) { repaint(); } public void startAnimation() {if ( animationTimer == null ) { currentImage = 0; animationTimer = new Timer( animationDelay, this ); animationTimer.start(); } else if ( ! animationTimer.isRunning() ) animationTimer.restart(); } public void stopAnimation() { animationTimer.stop(); } public Dimension getMinimumSize() { return getPreferredSize(); }

public Dimension getPreferredSize() { return new Dimension( 160, 80 ); } public static void main( String args[] ) { LogoAnimator anim = new LogoAnimator(); JFrame app = new JFrame( "Animator test" ); app.getContentPane().add( anim, Bord

erLayout.CENTER ); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); app.setSize( anim.getPreferredSize().width + 10, anim.getPreferredSize().height + 30 ); app.show(); } }

7 、 EJB Architecture

Exemple

// Definition of the EJB Remote Interface

package com.titan.cabin;import java.rmi.RemoteException;public interface Cabin extends javax.ejb.EJBObject { public String getName() throws RemoteException; public void setName(String str) throws RemoteException; public int getDeckLevel() throws RemoteException; public void setDeckLevel(int level)

throws RemoteException; public int getShip() throws RemoteException; public void setShip(int sp) throws RemoteException; public int getBedCount() throws RemoteException; public void setBedCount(int bc) throws RemoteException; }

//Interface CabinHome package com.titan.cabin;import java.rmi.RemoteException;import javax.ejb.CreateException;import javax.ejb.FinderException;public interface CabinHome extends javax.ejb.EJBHom

e { public Cabin create (int id) throws CreateException, RemoteException;

public Cabin findByPrimaryKey (CabinPK pk) throws FinderException, RemoteException;}

//Class CabinBean (a implement) package com.titan.cabin;import javax.ejb.EntityContext;public class CabinBean implements javax.ejb.EntityBean { public int id, deckLevel, ship, bedCount; public String name;

public CabinPK ejbCreate(int id){this.id = id; return null; } public void ejbPostCreate(int id){// Do nothing. Required.} public String getName(){ return name; } public void setName(String str){ name = str; } public int getShip(){ return ship; } public void setShip(int sp) { ship = sp; } public int getBedCount(){ return bedCount; } public void setBedCount(int bc){ bedCount = bc; } public int getDeckLevel(){ return deckLevel;} public void setDeckLevel(int level ){ deckLevel = level; }

public void setEntityContext(EntityContext ctx){ // Not implemented. } public void unsetEntityContext(){ // Not implemented. } public void ejbActivate(){ // Not implemented. } public void ejbPassivate(){ // Not implemented. } public void ejbLoad(){ // Not implemented. } public void ejbStore(){ // Not implemented. } public void ejbRemove(){ // Not implemented. }}

//Class Primary Key package com.titan.cabin;public class CabinPK implements java.io.Serializable { public int id; public int hashCode( ){ return id; } public boolean equals(Object obj){ if(obj instanceof CabinPK){ return (id == ((CabinPK)obj).id); } return false; } public String toString(){ return String.valueOf(id); }}

//(Deployment Descriptor) <?xml version="1.0"?> <!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterpri

se JavaBeans 1.1//EN" "http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd">

<ejb-jar> <enterprise-beans> <entity>

<description> This Cabin enterprise bean entity represents a

cabin on a cruise ship. </description> <ejb-name>CabinBean</ejb-name> <home>com.titan.cabin.CabinHome</home> <remote>com.titan.cabin.Cabin</remote>

<ejb-class>com.titan.cabin.CabinBean</ejb-class>

<persistence-type>Container</persistence-type> <prim-key-class>com.titan.cabin.CabinPK</prim-key-class><reentrant>False</reentrant><cmp-field><field-name>id</field-name></cmp-field> <cmp-field><field-name>name</field-name></cmp-field> <cmp-field><field-name>deckLevel</field-name></cmp-field><cmp-field><field-name>ship</field-name></cmp-field> <cmp-field><field-name>bedCount</field-name></cmp-field> </entity> </enterprise-beans><assembly-descriptor>

<security-role> <description> This role represents everyone who is allowed full

access to the cabin bean. </description>

<role-name>everyone</role-name> </security-role> <method-permission>

<role-name>everyone</role-name> <method><ejb-name>CabinBean</ejb-name>

<method-name>*</method-name> </method> </method-permission>

<container-transaction> <method>

<ejb-name>CabinBean</ejb-name> <method-name>*</method-name>

</method> <trans-attribute>Required</trans-attribute> </container-transaction>

</assembly-descriptor> </ejb-jar>

//Exempl of Client public class Client_1 { public static void main(String [] args){ try { Context jndiContext = getInitialContext(); Object obj = jndiContext.lookup("java:env/ejb/CabinHome"); CabinHome home = (CabinHome) javax.r

mi.PortableRemoteObject.narrow(obj, CabinHome.class); Cabin cabin_1 = home.create(1); System.out.println("created it!"); cabin_1.setName("Master Suite"); cabin_1.setDeckLevel(1); cabin_1.setShip(1); cabin_1.setBedCount(3); CabinPK pk = new CabinPK(); pk.id = 1; System.out.println("keyed it! ="+ pk);

Cabin cabin_2 = home.findByPrimaryKey(pk); System.out.println("found by key! ="+ cabin_2); System.out.println(cabin_2.getName()); System.out.println(cabin_2.getDeckLevel()); System.out.println(cabin_2.getShip()); System.out.println(cabin_2.getBedCount());

} catch (java.rmi.RemoteException re){re.printStackTrace();}

catch (javax.naming.NamingException ne){ne.printStackTrace();}

catch (javax.ejb.CreateException ce){ce.printStackTrace();}

catch (javax.ejb.FinderException fe){fe.printStackTrace();}

}

//Bean of Session:Travel Agent public interface TravelAgent extends javax.ejb.EJBObject { public void setCruiseID(int cruise) throws RemoteException, FinderException; public int getCruiseID()

throws RemoteException, IncompleteConversationalState; public void setCabinID(int cabin) throws RemoteException, FinderException; public int getCabinID()

throws RemoteException, IncompleteConversationalState; public int getCustomerID( )

throws RemoteException, IncompleteConversationalState; public Ticket bookPassage(CreditCard card, double price) throws RemoteException,IncompleteConversationalState; public String [] listAvailableCabins(int bedCount) throws RemoteException,IncompleteConversationalState;}