1 / 33

Java & Java Applets a brief introduction

Java & Java Applets a brief introduction. By Dereklis Leonidas for the Network Operations Center of Aristotle University of Thessalniki 18/4/2006. What is Java?.

toshikoj
Télécharger la présentation

Java & Java Applets a brief introduction

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java & Java Appletsa brief introduction By Dereklis Leonidas for the Network Operations Center of Aristotle University of Thessalniki 18/4/2006

  2. What is Java? • Java coffee is a coffee produced on the island of Java. is an island of Indonesia, and the site of its capital city, Jakarta. It is the most populous island in the world; indeed it has a larger population than either the continents of Australia or Antarctica (see the list of islands by population). en.wikipedia.org/wiki/Java_(coffee) • Java is a German-style board game designed by Wolfgang Kramer and Michael Kiesling and published in 2000 by Ravensburger in German and by Rio Grande Games in English. en.wikipedia.org/wiki/Java_(board_game) • Java is an object-oriented programming language developed initially by James Gosling and colleagues at Sun Microsystems. The language, initially called Oak (named after the oak trees outside Gosling's office), was intended to replace C++, although the feature set better resembles that of Objective C. Java should not be confused with JavaScript, which shares only the name and a similar C-like syntax. Sun Microsystems currently maintains and updates Java regularly. en.wikipedia.org/wiki/Java_(language)

  3. 1995: Java technology released to a select group on the Web site wicked.neato.orgThe San Jose Mercury News runs a front-page article about Java technologyName changed from "Oak" to "Java"Announced at Sun World -- Java technology is officially born 1996: The first JavaOneDeveloper ConferenceJDKtm 1.0 software is released1997: Over 220,000 downloads of JDK 1.1 software occur in just three weeksJavaOne draws 8,000 attendees, becoming the world’s largest developer conferenceJava Card 2.0 platform is unveiled1998: JDK 1.1 release downloads top 2 millionVisa launches world’s first smart card based on Java Card technologyThe Java Community Process (JCP) program formalized1999: Java 2 platform source code is releasedJavaOne draws 20,000J2EE beta software is released2000: Over 400 Java User Groups are established worldwideJava Developer Connection program tops 1.5 million membersSteve Jobs joins Scott McNealy on stage at JavaOne to announce a major commitment by Apple in support of Java technology2001: First international JavaOne conference in Yokohama JapanOver 1 million downloads of the Java Platform, Enterprise Edition (Java EE) SDK2002: J2EE SDK downloads reach 2 million78% of executives view J2EE technology as the most effective platform for building and deploying Web services2003: Java technology runs in almost 550 million desktopsAlmost 75% of professional developers use Java programming language as their primary development language2004: Java 2 Platform, Standard Edition 5 (Project Tiger) is releasedThe Java technology-powered Mars Rover (Spirit) touches down on MarsSun Java Studio Creator is launched2005: Java technology celebrates its 10th birthdayApproximately 4.5 million developers use Java technologyOver 2.5 billion Java technology-enabled devices are availablejava.com bundles the Google Toolbar with the JRE download

  4. Why Java? • Similar to C++ so it is familiar to commercial programmers. • Does not include the nasty dangerous parts of C++ so it is safe. • Extensive run-time type information and safe dynamic link-loading is available. • Includes string and multi-thread support in the language. • Automatic memory management. • Data type sizes and arithmetic behaviour are fixed and fully defined for all platforms. • Has useful standard OO libraries. • Documentation can be extracted from the source code. • Security checking is built in to the libraries and virtual machine. • Supports unicode for ease of internationalisation. • Write once, run anywhere, any platform (no porting, no client configuration .. well almost!) • Vast amount of supplier and programmer support and acceptance. It is unkillable. • Loads and runs over the WWW, 40 million potential clients.

  5. 1. The booleandata type may take one of the two values true or false 2. The char data type can take any value out of the character set of the computer system 3. There is also the String data type that can store strings. A variable type governs how much storage space is made available for the specific variable, for example int uses 32 bits, long and double use 64 bits

  6. Operators • Addition + • Subtraction - • Multiplication * • Division / • Modulus % • Equal to = = • Not equal to != • Greater than > • Less than < • Greater than or equal >= • Less than or equal <= • Java provides several operators for abbreviating assignment expressions • Addition assignment += //instead of x = x+5, x+=5 • Subtraction assignment -= • Multiplication assignment *= • Division assignment /= • Modulus assignment %=

  7. Boolean (Logical) Operators • Logical AND & or && • Logical OR | or || The difference is that with the double sign, if the first argument is false, the second is not checked. • Exclusive OR ^ • Logical NOT !

  8. How Java Runs?

  9. What are the main parts of a Java Application? • What we actually program in Java are CLASSES • Classes contain information of the future objects that will be created during execution • The structure of a Java class is the following • Declaration of Variables • Constructor(s) • Methods See example in the next page 

  10. Hello World Program class className{ //If it is a public class it must have the same name with the .java file //Variables String myString; //Constructor (has the same name as the class) public void className(){ myString = “Hello World”; /*This creates a string literal. If we want to create an object we write: myString = new String(“Hello World”);*/ } void display(){ //Void means it doesn’t return anything System.out.println(myString); } }

  11. How to run our program? This class will compile but it cannot run. Runnable classes in Java must contain a MAIN method. So to run our program we create a tester. Class myTester{ public static void main(String[] args){ className myClass = new className(); /*We create an object of type className giving it the name “myClass”*/ myClass.display(); //We run method “display” of //the object we created. } }

  12. Compiling and Running our Program Compile and Run To compile your program type: javac Ex1.java To run (execute) your program java Ex1

  13. Another simple example • The Java code public class Ex1 { public static void main(String args[]) { int Hours; int Rate; int GrossPay; Hours=40; Rate=4; GrossPay=Hours*Rate; System.out.println ("The Gross pay is : "+ GrossPay); } }

  14. Inheritance • Now let’s talk a little about inheritance • Java uses the EXTENDS keyword to declare inheritance from another class • A java class can inherit ONLY from ONE other class • If we inherit an abstract class (meaning an interface like the ActionListener()) we use the keyword IMPLEMENTS • Overiding is implemented by just creating a method with the same name and parameters as the inherited one • Overloading is implemented by creating a method with the same name but different parameters • Methods can be either friendly, default, public, private or protected. • Public: can be accessed from any other class • Protected: can be accessed from any other class in the same package • Private: can be accessed only by other methods in the same class

  15. Inheritance Example class VideoTape{ String title; // name of the item int length; // number of minutes boolean avail; // is the tape in the store? // constructor public VideoTape( String title, int length ) { this.title = title; this.length = length; avail = true; } public void show(){ System.out.println( title + ", " + length + " min. available:" + avail ); } } class Movie extends VideoTape{ String director; // name of the director String rating; // G, PG, R, or X // constructor public Movie( String title, int length, String director, String rating ){ super( title, length ); // use the super class's constructor this.director = director; this.rating = rating; // initialize what's new to Movie } }

  16. Applets An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a page. When you use a Java technology-enabled browser to view a page that contains an applet, the applet's code is transferred to your system and executed by the browser's Java Virtual Machine (JVM). For information and examples on how to include an applet in an HTML page, refer to this description of the <APPLET> tag.

  17. How to place an Applet in a WebPpage… In theory, <applet has been deprecated and you should use the more generic, verbose, error-prone <OBJECT tag. <OBJECT has some minor nice features, like a standby message and a way of providing alternate implementations if the user's browser does not support Java. It can work with serialised Applets. It works for languages and plug-ins other than Java. However, <OBJECT is still not as widely supported as <applet, so it is probably wiser to stick with <applet. See the HTML spec for details. <html> <body> <applet code = "testCircle.class" width="400" height="400"> </applet> </body> </html> The testCircle.class is the compiled .java file.

  18. An applet is an object that is used by another program, typically a Web browser. The Web browser is the application program and holds the main() method. The applet part of a Web page provides services (methods) to the browser when the browser asks for them. • An applet object has many instance variables and methods. Most of this is in the definition of Applet. To access these definitions, your program should import java.applet.Applet and java.awt.*. Here is the code for a small applet. The name of the class is Hamlet and the name of the source file is Hamlet.java. The definition of Applet provides a framework for building an applet. By itself, the class Applet does little that is visible in the Web browser. (It does a great many things behind the scenes, however.) • To build upon this framework, you import java.applet.Applet and extend the Applet class: • When you extend a class, you are making a new class by building upon a base class. This example defines a new class called Hamlet. The new class has everything in it that the class Applet has. • The class Applet has a paint() method, but that method does little. Objects of class Hamlet have their own paint() method because the definition in Hamlet.java overrides the one in Applet. • The Web browser calls the paint() method when it needs to "paint" the section of the monitor screen devoted to an applet. Each applet that you write has its own paint() method. 

  19. A simple example… import java.applet.Applet; import java.awt.*; public class Hamlet extends Applet{ public void paint ( Graphics gr ) { setBackground( Color.pink ); gr.drawString("To be", 25, 30); gr.drawString("or not to be,", 25, 50); gr.drawString("That is", 25, 70 ); gr.drawString("the question." ,25, 90); gr.drawString("--- Hamlet, W. Shakespeare" ,50, 130); } } Result 

  20. Now let’s see another example… import java.applet.Applet; import java.awt.*;// Assume that the drawing area is 300 by 150. // Draw ten red circles side-by-side across the drawing area. public class tenCircles extends Applet{ final int width = 300, height = 150; public void paint ( Graphics gr ){ gr.setColor( Color.red ); int radius = (width/10)/2;// the diameter is width/10 int Y = height/2 - radius; // the top edge of the squares int count = 0 ; while ( count < 10 ){ int X = count*(width/10); /* the left edge of each of 10 squares across the area*/ gr.drawOval( X, Y, 2*radius, 2*radius ); count = count + 1; } } } Result 

  21. import java.applet.*; import java.util.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class testReflexes extends Applet implements Runnable, MouseListener{ private JButton start;private JButton stop;private long rightNow;private boolean startPressed = false; private boolean stopCanBePressed = false;private int x; /*The random value.*/ private long tempTime = 0; private Thread myThread;private double highScore = 1000; public void init(){ try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }catch(Exception e){ try{ UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); }catch(Exception ex){ JOptionPane.showMessageDialog(null, "Sorry, cannot recognize Operating System!", "Error", JOptionPane.ERROR_MESSAGE); } } setLayout(null); setBackground(Color.blue); start = new JButton("Start"); stop = new JButton("Stop!"); start.setFocusable(false); stop.setFocusable(false); start.setBounds(getSize().width / 2 - 45, 50, 90, 25); stop.setBounds(getSize().width / 2 - 45, 150, 90, 25); start.addMouseListener(this); stop.addMouseListener(this); add(start); add(stop); }

  22. public void mouseReleased(MouseEvent e){} public void mousePressed(MouseEvent e){ String command = ((JButton)e.getSource()).getActionCommand(); if(command.equals("Start")){//If start Pressed. if(!startPressed){ startTime(); repaint(); }else{ JOptionPane.showMessageDialog(null, "Hey, don't be so anxious!\n You must press 'Stop'!", "Look Out!", JOptionPane.ERROR_MESSAGE); repaint(); } } if(command.equals("Stop!")){//If stop Pressed. if(startPressed){ if(stopCanBePressed){ stopTime(); startPressed = false; }else{ JOptionPane.showMessageDialog(null, "Hey, DON'T CHEAT!!!", "Look Out!", JOptionPane.ERROR_MESSAGE); repaint(); } }else{ JOptionPane.showMessageDialog(null, "Hey, you must first press 'Start'!", "Look Out!", JOptionPane.ERROR_MESSAGE); repaint(); } } }

  23. public void mouseExited(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void mouseClicked(MouseEvent e){} private void startTime(){ Random rnd = new Random(); x = (rnd.nextInt(10)+1)*1000; rightNow = System.currentTimeMillis(); myThread = new Thread(this); startPressed = true; myThread.start(); } private void stopTime(){ tempTime = System.currentTimeMillis(); JOptionPane.showMessageDialog(null, "It took you " + (tempTime - rightNow) / 1000.0 + " seconds!", "Result...", JOptionPane.INFORMATION_MESSAGE); if((tempTime - rightNow) / 1000.0 < highScore){ JOptionPane.showMessageDialog(null, "YOU MADE A NEW HIGH SCORE!", "Congatulations!", JOptionPane.INFORMATION_MESSAGE); highScore = ((tempTime - rightNow) / 1000.0); getAppletContext().showStatus("The current HighScore is " + highScore + "!"); } setBackground(Color.blue); stopCanBePressed = false; } public void run(){ while(tempTime < (rightNow + x)){ tempTime = System.currentTimeMillis(); } setBackground(Color.red); rightNow = System.currentTimeMillis(); stopCanBePressed = true; } public String getAppletInfo(){ return "Title: testReflexes\n"+"Author: Lord Achilles"; } }

  24. POSTing data using Java URL url;URLConnection urlConn;DataOutputStream printout;DataInputStreaminput;url = new URL (getCodeBase().toString() + "env.tcgi"); // URL of CGI-Bin script.urlConn = url.openConnection(); // URL connection channel.urlConn.setDoInput (true);// Let the run-time system (RTS) know that we want input.urlConn.setDoOutput (true); // Let the RTS know that we want to do output.urlConn.setUseCaches (false); // No caching, we want the real thing.urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Specify the content type.printout = new DataOutputStream (urlConn.getOutputStream ());   // Send POST output.String content ="name=" + URLEncoder.encode ("Buford Early") +"&email=" + URLEncoder.encode("buford@known-space.com");printout.writeBytes (content);printout.flush ();printout.close ();input = new DataInputStream (urlConn.getInputStream ());// Get response data.String str;while (null != ((str = input.readLine()))){System.out.println (str);textArea.appendText (str + "\n");}input.close ();

  25. What is a Servlet? A Java program that runs as part of a network service, typically on an HTTP server and responds to requests from clients. The most common use for a servlet is to extend a web server by generating web content dynamically. For example, a client may need information from a database; a servlet can be written that receives the request, gets and processes the data as needed by the client and then returns the result to the client. With the Java Web Server, servlets are placed in the servlets directory within the main JWS installation directory, and are invoked via http://host/servlet/ServletName. Note that the directory is servlets, plural, while the URL refers to servlet, singular. Since this example was placed in the hall package, it would be invoked via http://host/servlet/hall.HelloWorld. Other Web servers may have slightly different conventions on where to install servlets and how to invoke them. Most servers also let you define aliases for servlets, so that a servlet can be invoked via http://host/any-path/any-file.html. The process for doing this is completely server-specific; check your server's documentation for details.

  26. What are the Advantages of Servlets Over “Traditional CGI?” Java servlets are more efficient, easier to use, more powerful, more portable, and cheaper than traditional CGI and than many alternative CGI-like technologies. (More importantly, servlet developers get paid more than Perl programmers :-). Efficient. With traditional CGI, a new process is started for each HTTP request. If the CGI program does a relatively fast operation, the overhead of starting the process can dominate the execution time. With servlets, the Java Virtual Machine stays up, and each request is handled by a lightweight Java thread, not a heavyweight operating system process. Similarly, in traditional CGI, if there are N simultaneous request to the same CGI program, then the code for the CGI program is loaded into memory N times. With servlets, however, there are N threads but only a single copy of the servlet class. Servlets also have more alternatives than do regular CGI programs for optimizations such as caching previous computations, keeping database connections open, and the like. 

  27. Convenient. Hey, you already know Java. Why learn Perl too? Besides the convenience of being able to use a familiar language, servlets have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such utilities. Powerful. Java servlets let you easily do several things that are difficult or impossible with regular CGI. For one thing, servlets can talk directly to the Web server (regular CGI programs can't). This simplifies operations that need to look up images and other data stored in standard places. Servlets can also share data among each other, making useful things like database connection pools easy to implement. They can also maintain information from request to request, simplifying things like session tracking and caching of previous computations. Portable. Servlets are written in Java and follow a well-standardized API. Consequently, servlets written for, say I-Planet Enterprise Server can run virtually unchanged on Apache, Microsoft IIS, or WebStar. Servlets are supported directly or via a plugin on almost every major Web server. Inexpensive. There are a number of free or very inexpensive Web servers available that are good for "personaluse or low-volume Web sites. However, with the major exception of Apache, which is free, most commercial-quality Web servers are relatively expensive. Nevertheless, once you have a Web server, no matter the cost of that server, adding servlet support to it (if it doesn't come preconfigured to support servlets) is generally free or cheap.

  28. A simple Example package hall; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWWW extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n" + "<HTML>\n" + "<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>Hello WWW</H1>\n" + "</BODY></HTML>"); } } http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-First-Servlets.html

  29. Introduction to Programming • Some Useful Internet Addresses • www.javasoft.com • www.java.sun.com • www.Javaworld.com These two sites have been merged

  30. That’s all folks! Good Easter and even better Lamb!

More Related