Presentation is loading. Please wait.

Presentation is loading. Please wait.

第十四章 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.

Similar presentations


Presentation on theme: "第十四章 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."— Presentation transcript:

1 第十四章 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 7.EJB

2 1 、 J2EE 1.3 APIs and Technologies

3 2 、 N-tier J2EE Architecture

4 2 、 Application distribute multi-tier

5 2 、 J2EE Containers & Components

6 3 、 J2EE Application Development Lifecycle Write and compile component code Servlet, JSP, EJB Write deployment descriptors for components Assemble components into ready-to- deployable package Deploy the package on a server

7 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

8 JSP scripting elements There is more than one type of JSP “ tag, ” depending on what you want done with the Java The expression is evaluated and the result is inserted into the HTML page The code is inserted into the servlet's service method This construction is called a scriptlet The declarations are inserted into the servlet class, not into a method

9 Example JSP Hello! The time is now 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

10 Example Hello World Example Hello World Example Hello !

11 Page is in the proj web application: tomcat_home/webapps/proj/HelloWorld.jsp Invoked with URL: http:// : /proj/HelloWorld.jsp?name=snoopy

12 Invoked with URL (no parameter): http:// : /proj/HelloWorld.jsp

13 Variables You can declare your own variables, as usual JSP provides several predefined variables request : The HttpServletRequest parameter response : The HttpServletResponse parameter session : The HttpSession associated with the request, or null if there is none out : A JspWriter (like a PrintWriter) used to send output to the client Example: Your hostname:

14 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

15 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!

16 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

17 5 、 Servlet The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little HTML mixed in The HTML is enclosed in out.println( ) statements

18 A “Hello World” servlet public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = " \n";out.println(docType + " \n" + " Hello \n" + "<BODY BGCOLOR= \"#FDF5E6\">\n" + " Hello World \n" + " "); }} This is mostly Java with a little HTML mixed in

19 // HTTPGetServlet.java: Creating and sending a page //to the client import 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

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

21 Servlet HTTP GET Example <FORM ACTION="http://localhost:8080/ servlet/HTTPGetServlet" METHOD="GET"> Click the button to have the servlet send an HTML document

22 Relationships In servlets: HTML code is printed from java code In JSP pages: Java code is embedded in HTML code Java HTML Java HTML

23 6 、 JavaBean // LogoAnimator.java: Animation bean package 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;

24 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(); }

25 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; }

26 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(); }

27 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, BorderLayout.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(); } }

28 7 、 EJB Architecture

29

30 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; }

31 //Interface CabinHome package com.titan.cabin; import java.rmi.RemoteException; import javax.ejb.CreateException; import javax.ejb.FinderException; public interface CabinHome extends javax.ejb.EJBHome { public Cabin create (int id) throws CreateException, RemoteException; public Cabin findByPrimaryKey (CabinPK pk) throws FinderException, RemoteException; }

32 //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; }

33 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. }

34 //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); }

35 //(Deployment Descriptor) This Cabin enterprise bean entity represents a cabin on a cruise ship. CabinBean com.titan.cabin.CabinHome com.titan.cabin.Cabin com.titan.cabin.CabinBean

36 Container com.titan.cabin.CabinPK False id name deckLevel ship bedCount This role represents everyone who is allowed full access to the cabin bean.

37 everyone everyone CabinBean * CabinBean * Required

38 //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.rmi.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);

39 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();} }

40 //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; }


Download ppt "第十四章 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."

Similar presentations


Ads by Google