What is java
This presentation is the property of its rightful owner.
Sponsored Links
1 / 48

WHAT is JAVA PowerPoint PPT Presentation


  • 55 Views
  • Uploaded on
  • Presentation posted in: General

WHAT is JAVA. What is Java?. O bject -oriented programming (OOP) language developed by SUN Microsystems Similar to C and C++, except without some of the confusing, poorly understood features of C++ Extensive networking facilities

Download Presentation

WHAT is JAVA

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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


What is java

WHAT is JAVA


What is java1

What is Java?

  • Object-oriented programming (OOP) language developed bySUN Microsystems

  • Similar to C and C++, except without some of the confusing,poorly understood features of C++

  • Extensive networking facilities

  • Extensive set of APIs for GUIs, distributed computing, 2D/3Dgraphics, mail, and others

  • Portable: Write Once, Run Anywhere

  • Multithreading support built into the language


Java features

Java Features

  • Automatic garbage collection

    • No manual memory allocation and deallocation

    • Never have to worry about memory leaks

  • No pointers or pointer arithmetic

    • No off-by-one bugs

  • Arrays are first-class objects

    • Array bounds are always checked

  • Multiple inheritance replaced by interfaces

    • Eliminates complexities of multiple inheritance


Features removed from c

Features removed from C++

  • No typedefs, defines or preprocessor

  • No header files

  • No structures or unions

  • No enums

  • No functions - only methods in classes

  • No multiple inheritance

  • No goto

  • No operator overloading (except “+” for string concatenation)

  • No automatic type conversions (except for primitive types)

  • No pointers


Java virtual machine

Java Virtual Machine

  • Java is compiled into bytecodes

  • Bytecodes are high-level, machine-independent instructions for ahypothetical machine, the Java Virtual Machine (JVM)

  • The Java run-time system provides the JVM

  • The JVM interprets the bytecodes during program execution

  • Since the bytecodes are interpreted, the performance of Javaprograms slower than comparable C/C++ programs

  • But the JVM is continually being improved and new techniquesare achieving speeds comparable to native C++ code


Types of java programs

Types of Java Programs

  • Application

    • Standalone Java program that can run independent of any Web browser

  • Applet

    • Java program that runs within a Java-enabled Web browser

  • Servlet

    • Java software that is loaded into a Web server to provide additional serverfunctionality ala CGI programs


The hello world program

The Hello World Program

  • Create source file: Hello.java

  • public class Hello {

  • public static void main (String args[]) {

  • System.out.println("Hello World!");

  • }

  • }

  • Note that the name of the file is the name of the public class witha .java extension added

  • Compile: javac Hello.java

  • Produces the class file Hello.class

  • Run: java Hello

  • Starts up the JVM

    • Note that the .class extension is not specified


Some java oo technology

Some Java OO Technology

  • Class - collection of data (attributes) and methods that operate onthat data

  • Member - either an attribute or a method of a class

  • Public Member - member which is accessible by any method inany class

  • Private Member - member which is accessible only by methodsdefined within the class

  • Public Class - class that is visible everywhere and can be used byany method in any class

  • Object - instance of a class

  • Object Instantiation - the creation of a new object


Some java oo technology1

Some Java OO Technology

  • Constructor - method which performs object initialization (notcreation!)

  • Object Reference - variable that holds a reference to (really thememory address of) an object

  • Instance Variable - attribute for which each object (instance) hasits own copy

  • Class Variable - attribute for which there is only one copy for theclass.

  • Each object (instance) shares this copy. Also called astatic variable


Some java oo technology2

Some Java OO Technology

  • Instance Method - method which operates on the attributes of anobject (instance)

  • Class Method - method which does not operate on a particularobject, but performs some utility function or operates on staticvariables. Also called a static method.

  • Method Signature - the number, type and order of arguments of amethod

  • Method Overloading - defining a method with the same name butdifferent signature as another method in the same class


Download install the java sdk or jdk

Download & Install the JavaSDK (or JDK)

  • Recommended Java version– JDK 1.6

  • Obtain at http://java.com/en/download/index.jsp

  • Minimum supported Java version

  • – Servlets 2.3 and JSP 1.2 (standalone servers).

    • Java 1.2 or later.

  • – J2EE 1.3 (which includes servlets 2.3 and JSP 1.2).

    • Java 1.3 or later.

  • – Servlets 2.4 and JSP 2.0 (standalone servers).

    • Java 1.3 or later.

  • – J2EE 1.4 (which includes servlets 2.4 and JSP 2.0).

    • Java 1.4 or later.


Server setup and configuration

Server Setup and Configuration

  • Download and install the Java SoftwareDevelopment Kit (SDK)

  • Download a server.

  • Configure the server

  • Set up your development environment

  • Test your setup

  • Establish a simplified deployment method

  • Create custom Web applications


Download a free server for your desktop

Download a Free Serverfor Your Desktop

  • Apache Tomcat

    • – http://jakarta.apache.org/tomcat/

    • – For installation and setup details, see

      http://www.coreservlets.com/Apache-Tomcat-Tutorial/

  • Macromedia JRun

    • – http://www.macromedia.com/software/jrun/

  • Caucho Resin

    • – http://caucho.com/products/resin/

  • New Atlanta ServletExec

    • – http://www.newatlanta.com/products/servletexec/

  • Jetty

    • – http://jetty.mortbay.org/jetty/


Apache tomcat

Apache Tomcat

  • Apache Tomcat is developed in an open and participatory environment and released under the Apache License version 2.

  • Apache Tomcat is intended to be a collaboration of the best-of-breed developers from around the world.

  • Apache Tomcat powers numerous large-scale, mission-critical web applications across a diverse range of industries and organizations.

  • Some of these users and their stories are listed on the PoweredBy wiki page.


Apache tomcat1

Apache Tomcat

  • Setup Tomcat 5.0.27 on your computer. 

  • Download from http://www.coreservlets.com/Apache-Tomcat-Tutorial/index.html.

  • Unzip into the top level of the C drive.

  • Set JAVA_HOME

  • Set this environment variable to point at the top-level of your Java installation directory (e.g.,C:\Program Files\Java\jdk1.7.0_03).

  • Use the Control Panel or start this 


Apache tomcat2

Apache Tomcat

  • Test the server.

  • Make sure you can start/stop the server. Test some sample HTML files, JSP pages, and servlets.

  • For Tomcat, click oninstall_dir/bin/startup.bat. Next, enter the URL http://localhost/ in your browser and make sure you get the Tomcat welcome page,

  • not an error message saying that the page could not be displayed or that the server could not be found.


Configure the server

Configure the Server

  • Identify the SDK installation directory.

    • – For Tomcat: set JAVA_HOME

  • Specify the port.

    • – Change the port from default (usually 8080) to 80

  • Make server-specific customizations.

    • – For Tomcat:

      • Enable servlet reloading

      • Enable the ROOT context

      • Turn on the invoker servlet

      • See book or refer to http://www.coreservlets.com/ApacheTomcat-Tutorial/


Set up your development environment

Set Up Your DevelopmentEnvironment

  • Create a development directory

    • – Choose a location in which to develop your servlets, JSP

      documents, and supporting classes (e.g., C:\Servlets+JSP)

  • Set your CLASSPATH

    • – Tell the compiler about the servlet and JSP JAR file and

      the location of your development directory.

    • – Setting this variable incorrectly is the single mostcommon cause of problems for beginners.

  • Make shortcuts to start and stop the server

    • – Make sure it is convenient to start and stop the server.

  • Bookmark or install the servlet and JSP APIdocumentation

    • – You’ll refer to this documentation frequently, so keep ithandy.


Test your setup

Test Your Setup

  • Verify your Java installation

  • – Be sure that you get meaningful results for both of these:

    • java -version

    • javac -help

  • Check your basic server configuration

    • – Start server and access the server home page

      (http://localhost/)

    • – Access a simple user-defined HTML page

      • Download Hello.html from book's source code archive

      • Put in install_dir/webapps/ROOT

      • Access with http://localhost/Hello.html

    • – Access a simple user-defined JSP page

      • Download Hello.jsp and put in install_dir/webapps/ROOT

      • Access with http://localhost/Hello.jsp


  • Test your setup1

    Test Your Setup

    • Compile and deploy a packagelessservlet

      – Download HelloServlet.java from source code archive

      – Place in development directory (e.g., C:\Servlets+JSP)

      – Compile (if errors, check CLASSPATH)

      – Move HelloServlet.class to

      install_dir/webapps/ROOT/WEB-INF/classes

      – Access with http://localhost/servlet/HelloServlet


    Test your setup2

    Test Your Setup

    • Compile and deploy a packaged servlet

      • – Download HelloServlet2.java from source code archive

      • – Place in coreservlets subdirectory of development

        directory (e.g., C:\Servlets+JSP\coreservlets)

        – Compile (if errors, check CLASSPATH)

        – Move HelloServlet2.class toinstall_dir/webapps/ROOT/WEBINF/classes/coreservlets

        – Access with

        http://localhost/servlet/coreservlets.HelloServlet2


    Test your setup3

    Test Your Setup

    • Compile and deploy a packaged servlet that

      uses a helper class

      • – Download HelloServlet3.java and ServletUtilities.java

      • – Place in coreservlets subdirectory of development dir

      • – Compile (if errors, check CLASSPATH)

      • – Move both class files to

        install_dir/webapps/ROOT/WEBINF/classes/coreservlets

      • – Access with

        http://localhost/servlet/coreservlets.HelloServlet3


    A servlet s job

    A Servlet’s Job

    • Read explicit data sent by client (form data)

    • Read implicit data sent by client

      (request headers)

    • Generate the results

    • Send the explicit data back to client (HTML)

    • Send the implicit data to client

      (status codes and response headers)


    The advantages of servlets over traditional cgi

    The Advantages of ServletsOver “Traditional” CGI

    • Efficient

      – Threads instead of OS processes, one servlet copy

    • • Convenient

      • – Lots of high-level utilities

    • • Powerful

      • – Sharing data, pooling, persistence

    • • Portable

      • – Run on virtually all operating systems and servers

    • • Inexpensive

      • – There are plenty of free and low-cost servers

    • • Secure

      • – No shell escapes, no buffer overflows


    Mainstream

    Mainstream

    • Popular:

      • – The single most common use of Java technology

      • – The leading technology for medium/large Web applications

    • • Supported by:

      • – Apache, Oracle, IBM, Sybase, BEA, Macromedia, Caucho,

      • Sun/iPlanet, New Atlanta, ATG, Fujitsu, Lutris, Silverstream, the

      • World Wide Web Consortium (W3C), and many others

      • – Plugins for IIS and Zeus

    • • Runs on:

      • – Windows, Unix/Linux, MacOS,VMS, and IBM mainframe OSs

    • • Used for:

      • – Airline companies, hotels,e-commerce sites, search engines,

        banks, financial sites, etc., etc., etc.


    Extending the power of servlets javaserver pages jsp

    Extending the Power of Servlets:JavaServer Pages (JSP)

    • Uses of JSP ConstructsUses of JSP Constructs

    • Scripting elements calling servletcode directly

    • Scripting elements calling servletcode indirectly (by means of utilityclasses)

    • Beans

    • Servlet/JSP combo (MVC)

    • MVC with JSP expression language

    • Custom tags


    Extending the power of servlets javaserver pages jsp1

    Extending the Power of Servlets:JavaServer Pages (JSP)

    • Idea:

    • – Use regular HTML for most of page

    • – Mark dynamic content with special tags

    • <HTML>

    • <HEAD><TITLE>Welcome to Our Store</TITLE></HEAD>

    • <BODY>

    • <H1>Welcome to Our Store</H1>

    • <SMALL>Welcome,

    • <!-- User name is "New User" for first-time visitors -->

    • <%= coreservlets.Utils.getUserNameFromCookie(request) %>

    • To access your account settings, click

    • <A HREF="Account-Settings.html">here.</A></SMALL>

    • <P>

    • Regular HTML for rest of on-line store’s Web page

    • </BODY></HTML>


    Basic syntax

    Basic Syntax

    • HTML Text

      • – <H1>Blah</H1>

      • – Passed through to client. Really turned into servlet code

    • that looks like

      • out.print("<H1>Blah</H1>");

  • HTML Comments

    • – <!-- Comment -->

    • – Same as other HTML: passed through to client

  • JSP Comments

    • – <%-- Comment --%>

    • – Not sent to client

  • To get <% in output, use <\%


  • Types of scripting elements

    Types of Scripting Elements

    Expressions

    • – Format: <%= expression %>

    • – Evaluated and inserted into the servlet’s output.

      I.e., results in something like out.print(expression)

  • Scriptlets

    • – Format: <% code %>

    • – Inserted verbatim into the servlet’s _jspService method(called by service)

  • Declarations

    • – Format: <%! code %>

    • – Inserted verbatim into the body of the servlet class,outside of any existing methods


  • Jsp expressions

    JSP Expressions

    • Format

    • – <%= Java Expression %>

    • Result

    • – Expression evaluated, converted to String, and placed

      into HTML page at the place it occurred in JSP page

    • – That is, expression placed in _jspService inside out.print

    • Examples

    • – Current time: <%= new java.util.Date() %>

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

    • XML-compatible syntax

    • – <jsp:expression>Java Expression</jsp:expression>

    • – You cannot mix versions within a single page. You must

      use XML for entire page if you use jsp:expression.


    Jsp servlet correspondence

    JSP/Servlet Correspondence

    • Original JSP

    • <H1>A Random Number</H1>

    • <%= Math.random() %>

    • Representative resulting servlet code

    • public void _jspService(HttpServletRequest request,

    • HttpServletResponse response)

    • throws ServletException, IOException {

    • response.setContentType("text/html");

    • HttpSession session = request.getSession(true);

    • JspWriter out = response.getWriter();

    • out.println("<H1>A Random Number</H1>");

    • out.println(Math.random());

    • ...

    • }


    Hello web app

    Hello Web App

    • As a first web application, we'll use the Hello World example :

    • Create a directory called hello within webapps, then within that create a file called Hello.jsp. 

    • Copy the following text into it:

    • <html>

    • <head> <title> Hello JSP </title> </head>

    • <body>

    • <p> Hello World: <%= new java.util.Date() %> </p>

    • </body>

    • </html>


    Hello web app1

    Hello Web App

    Now click on this URL: http://localhost/hello/Hello.jsp, and you should see a page like this one:


    Jsp expressions example

    JSP Expressions: Example

    • <HTML> <BODY>

    • <H2>JSP Expressions</H2>

    • <UL>

    • <LI>Current time: <%= new java.util.Date() %>

    • <LI>Server: <%= application.getServerInfo() %>

    • <LI>Session ID: <%= session.getId() %>

    • <LI>The <CODE>testParam</CODE> form parameter:

    • <%= request.getParameter("testParam") %>

    • </UL>

    • </BODY></HTML>


    Predefined variables

    Predefined Variables

    • request

    • – The HttpServletRequest (1st argument to service/doGet)

    • response

    • – The HttpServletResponse (2nd arg to service/doGet)

    • out

    • – The Writer (a buffered version of type JspWriter) used to

      send output to the client

    • session

    • – The HttpSession associated with the request (unless

    • disabled with the session attribute of the page directive)

    • application

    • – The ServletContext (for sharing data) as obtained via

    • getServletContext().


    Jsp declarations example

    JSP Declarations: Example

    • <!DOCTYPE …>

    • <HTML>

    • <HEAD>

    • <TITLE>JSP Declarations</TITLE>

    • <LINK REL=STYLESHEET HREF="JSP-Styles.css“ TYPE="text/css">

    • </HEAD>

    • <BODY>

    • <H1>JSP Declarations</H1>

    • <%! private int accessCount = 0; %>

    • <H2>Accesses to page since server reboot:

    • <%= ++accessCount %></H2>

    • </BODY></HTML>


    Making custom web apps

    Making Custom Web Apps

    • Make a directory whose structure mirrorsthe structure of the default Webapplication.

      • HTML (and, eventually, JSP) documents go in the toplevel directory (e.g. sample)

      • apache-tomcat-1.6.028/webapp/sample

      • The web.xml file goes in the WEB-INF subdirectory

      • Servlets and other classes go either in WEB-INF/classes

        or a subdirectory of WEB-INF/lib that matches thepackage name.

      • On Tomcat, entire directory goes in install_dir/webapps

      • Update your CLASSPATH.

      • Add webAppDir/WEB-INF/classes to it.


    Making custom web apps1

    Making Custom Web Apps

    • Use the directory name in the URL

    • • All URLs should be of the formhttp://host/webAppDir/…

    • • Use web.xml to assign custom URLs

      • • Use the servlet and servlet-mapping elements

    • <servlet>

    • <servlet-name>Servlet2</servlet-name>

    • <servlet-class>

    • coreservlets.HelloServlet2

    • </servlet-class>

    • </servlet>

    • <servlet-mapping>

    • <servlet-name>Servlet2</servlet-name>

    • <url-pattern>/servlet2</url-pattern>

    • </servlet-mapping>


    The servlet life cycle

    The Servlet Life Cycle

    • init

      • – Executed once when the servlet is first loaded.

      • Not called for each request.

    • service

      • – Called in a new thread by server for each request.

      • Dispatches to doGet, doPost, etc.

      • Do not override this method!

    • doGet, doPost, doXxx

      • – Handles GET, POST, etc. requests.

      • – Override these to provide desired behavior.

    • destroy

      • – Called when server deletes servlet instance.

      • Not called after each request.


    The role of form data

    The Role of Form Data

    • Example URL at online travel agent

      • http://host/path?user=Marty+Hall&origin=bwi&dest=lax

      • Names come from HTML author; values from end user

    • Parsing form (query) data in traditional CGI

      • – Read the data one way (QUERY_STRING) for GET

        requests, another way (standard input) for POST requests

      • – Chop pairs at ampersands, then separate parameter names

        (left of the =) from parameter values (right of the =)

      • – URL decode values (e.g., "%7E" becomes "~")

    • Greatly simplified in servlets

      • – Use request.getParameter in all cases.

      • – Gives URL-decoded result


    Creating form data html forms

    Creating Form Data:HTML Forms

    • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0Transitional//EN">

    • <HTML>

    • <HEAD><TITLE>A Sample Form Using GET</TITLE></HEAD>

    • <BODY BGCOLOR="#FDF5E6">

    • <H2 ALIGN="CENTER">A Sample Form Using GET</H2>

    • <FORM ACTION="http://localhost:8088/SomeProgram">

    • <CENTER>

    • First name:

    • <INPUT TYPE="TEXT" NAME="firstName" VALUE="Joe"><BR>

    • Last name:

    • <INPUT TYPE="TEXT" NAME="lastName" VALUE="Hacker"><P>

    • <INPUT TYPE="SUBMIT"> <!-- Press this to submit form -->

    • </CENTER></FORM>

    • </BODY></HTML>


    Installing html files

    Installing HTML Files

    • HTML files do not go in WEB-INF/classes

      • – They go in directory that contains WEB-INF

    • Tomcat

      • – install_dir\webapps\ROOT\Form.html or

      • – install_dir\webapps\ROOT\SomeDir\Form.html

    • URL

      • – http://localhost/Form.html or

      • – http://localhost/SomeDir/Form.html

    • Custom Web applications

      • – Use a different dir with the same structure as the default

    • Web app

      • – Use directory name in URL (http://host/dirName/…)


    Sending post data

    Sending POST Data

    • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0Transitional//EN">

    • <HTML>

    • <HEAD><TITLE>A Sample Form Using POST</TITLE></HEAD>

    • <BODY BGCOLOR="#FDF5E6">

    • <H2 ALIGN="CENTER">A Sample Form Using POST</H2>

    • <FORM ACTION="http://localhost:8088/SomeProgram"

    • METHOD="POST">

    • <CENTER>

    • First name:

    • <INPUT TYPE="TEXT" NAME="firstName" VALUE="Joe"><BR>

    • Last name:

    • <INPUT TYPE="TEXT" NAME="lastName" VALUE="Hacker"><P>

    • <INPUT TYPE="SUBMIT">

    • </CENTER>

    • </FORM>

    • </BODY></HTML>


    Reading form data in servlets

    Reading Form Data In Servlets

    • request.getParameter("name")

      • – Returns URL-decoded value of first occurrence of name

        in query string

      • – Works identically for GET and POST requests

      • – Returns null if no such parameter is in query data

    • request.getParameterValues("name")

      • – Returns an array of the URL-decoded values of all

    • occurrences of name in query string

      • – Returns a one-element array if param not repeated

      • – Returns null if no such parameter is in query

    • request.getParameterNames() orrequest.getParameterMap()

      • – Returns Enumeration or Map of request params

      • – Usually reserved for debugging


    Handling input in multiple languages

    Handling Input in MultipleLanguages

    • Use server's default character set

      • String firstName = request.getParameter("firstName");

    • Convert from English (Latin-1) to Japanese

      • String firstNameWrongEncoding =

    • request.getParameter("firstName");

      • String firstName =

    • new String(firstNameWrongEncoding.getBytes(),"Shift_JIS");

    • Accept either English or Japanese

    • request.setCharacterEncoding("JISAutoDetect");

    • String firstName =

    • request.getParameter("firstName");


    Reading raw form data and parsing uploaded files

    Reading Raw Form Data andParsing Uploaded Files

    • Raw data

      • – request.getReader

      • – request.getInputStream

        • • Data no longer available via getParameter after this

    • Parsing uploaded files

      • – HTML has a way of submitting entire files

    • <INPUT TYPE="FILE"…>

      • – Servlet/JSP APIs have no builtin way to parse files

      • – Popular third-party library available from theApache/Jakarta “Commons” library

        • http://jakarta.apache.org/commons/fileupload/


    An html form with three parameters

    An HTML Form With ThreeParameters

    • <FORM ACTION="/servlet/coreservlets.ThreeParams">

    • First Parameter: <INPUT TYPE="TEXT" NAME="param1"><BR>

    • Second Parameter: <INPUT TYPE="TEXT" NAME="param2"><BR>

    • Third Parameter: <INPUT TYPE="TEXT" NAME="param3"><BR>

    • <CENTER><INPUT TYPE="SUBMIT"></CENTER>

    • </FORM>


    Reading the three parameters

    Reading the Three Parameters

    • public class ThreeParams extends HttpServlet {

    • public void doGet(HttpServletRequest request,

    • HttpServletResponse response)

    • throws ServletException, IOException {

    • out.println(docType + "<HTML>\n" +

    • "<HEAD><TITLE>"+title + "</TITLE></HEAD>\n" +

    • "<BODY BGCOLOR=\"#FDF5E6\">\n" +

    • "<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +

    • "<UL>\n" +" <LI><B>param1</B>: "

    • + request.getParameter("param1") + "\n" + " <LI><B>param2</B>: "

    • + request.getParameter("param2") + "\n" + " <LI><B>param3</B>: "

    • + request.getParameter("param3") + "\n" + "</UL>\n" +

    • "</BODY></HTML>"); }}


  • Login