Netzwerkprogrammierung mit Java - Part2

zurück zu java and internet part 1 <--- ---> zur Java Übersicht

HTML (HyperText Markup Language)

<html>
 
<head>
   <META HTTP_EQUIV="content-type" CONTENT="text/html;charset=iso-8859-1">
   <title> Titel der Seite </title>
 </head>

 <body gbcolor = "#FFCCFF">
   <h1> gross geschriebener Text </h1>
   <! -- einzeiliger Kommentar -- >
   normaler Text <br>
   nach Zeilenumbruch geht's weiter
  <p> neuer Abschnitt

   <! -- mehrzeiliger
               Kommentar //-- >

   <a href=http://java.sun.com/> das isch en Link </a>

  <form method="get" action="/cgi-bin/search.pl">
   Suche: <input type="text" name="name" size="35" maxlength="35" value"">
   <br>
   <select name="zone">
                <option value="All" selected>All</option>
                <option value="section">Section</option>
   </select><br>
   <input type="submit" value=Search">
   <input type="reset" value="Reset">
 </body>
</html>

URL: protokoll://username:password@rechneradresse:serverport/dokument

Cascading Style Sheets (CSS)

<style type="text/css">                                         //Externel Style sheet
  H1 {color:blue; don't-style:bold}                          //Document-Level Style
  H2 {color:red; font-style:italic}                             //Inline Style

 @import url(http://www.w3.org/StyleSheets/Core/Oldstyle.css);
</style>

Javascript

<SCRIPT LANGUAGE="JavaScript"><! --
 document.write(" hello world ");
 // Einzeiliger Kommentar
/* ausdokumentieren von Code
 function display_time_in_status_line () {                             //Every function is a Object-> Functionprototypes
  var d = new Date(); var t = d.getHours() + ":" + d.getMinutes();
 defaultStatus = t; //time in status line
 setTimeout ("display_time_in_status_line ()", 10000); //update every 10 seconds
*/

// - - > </SCRIPT>

<body onLoad="display_time_in_status_line();">

Schlüsselwörter

break       false        in             this          void
continue  for           new        true         while
delete      function   null          typeof     with
else         if              return      var

Datentypen

Number   String      boolean   Function  Object
Array      null          undefined

Array

var a = new Object();
a[0] = 10;
a[2] = 'Hello';
a[100] = true;
var a2 = new Array(1, "hello", true);

Assoziativarray
var a= new Object();
a["height"] = 10;
a["width"] = 20;

s1 = a.join  // join wandelt alle Elemente in Strings um
                // reverse kehr den Inhalt eines Arrays um
                //sort , sortiert Alphabetisch

Kontrollanweisungen

if( boolean)
  statement
else
  statement

while(boolean)
  statement

for(initialize; test; action)
  statement

for(variable in object)
  statement

break
continue

with(object)
  statement

function funcname([arg_1 [, arg_n]])
{ statement }

return [ expression]

EventHandler

Link         onClick()                 onMouseOut()        onMouseOver()
Button     onBlur()                  onClick()                 onFocus()

Objekt window

Membervariablen:
                self,window           //aktuelles Fenster
                defaultstatus          //Inhalt der Statusbar, solange nichts anderes definiert z.B lade bild.gif
                document                               //angezeigtes Dokument                        //z.B document.write(); document.writeln();
                location                   //angezeigte URL                                   // .appCodeName, appName, appVersion
                navigatior                               //Browser-Objekt
                status                     //Statuszeile

Methoden:
                alert()                      //Meldung in Dialogfenster                     onMouseOver = method( )
                confirm()                 //OK/Cancel Dialog                                 onMouseOut = method( )
                prompt()                  //fragt Benutzer nach String 
               open()                     //öffnet neues Fenster
                close()                    //schliesst das aktuelle Fenster

Webserver und CGI (Common Gateway Interface)

Standard-Konfiguration

ServerType standalone
ServerRoot "d:/Apache"
Port 80
#User nobody
#Group nobody
Server Admin sschneid@suvi.org
#ServerName www.suvi.org
DocumentRoot "f:/Apache&htdocs"
DirectoryIndex index.html index.htm
AccessFileName .htacces
HeaderName HEADER
ReadmeName README
IndexIgnore .???* ~ # HEADER* README* RCS CVS *,v *,t

<VirtualHost www.hello.com>
 ServerAdmin webmaster@hello.com
 DocumentRoot "f:/Apache/hello.com/htdocs"
 ServerName www.hello.com
 ErrorLog "d:/Apache/logs/hello.com.error_log
 TransferLog "d:/Apache/logs/hello.com/transfer_log"
</VirtualHost>

Introduction to Perl

Beispiel Hello World

#!/usr/bin/perl -w                                   # -w compiler switch to turn warnings on
#
# comment
if ($#ARGV >= 0) {who = join(, ,,@ARGV); }
else { $who = 'World'; }
print "Hello, $who!\n";
>Hello World  // oder Hello $ARGV

Arrays

('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri','Sat')
(13,14,15,16,17,18,19) equivalent to (13..19)
(13,14,15,16,17,18,19)[2..4] equivalent to (15,16,17)

Associative arrays

@days = (31,28,31,30,31,30,31,31,30,31,30,31);
                               # A list whith 12 elements.
$#days                   # Last index of @days; 11 for above list
$#days = 7             # shortens of lengthens list @days to 8 elements
@days                    # ($days[0], $days[1],..)
@days[3,4,5]          # = (30,31,30)
@days{'a','c'}         # same as ($days{'a'}, $days{'c'})
%days                    # (key1, value1, key2, value2, ...)

Expressions

$a = 5;
   $a++;                   # $a is now 6; we added 1 to it.
   $a += 10;             # Now it's 16; we added 10.
   $a /= 2;                # And divided it by 2, so it's 8.

Search and replace

$pet = "I love my cat.\n";
    $pet =~ s/cat/dog/;
    print $pet;

Variable $_

$_,$1,$2,$3 sind implizite variablen mit spezieller Bedeutung.

<STDIN>; assigns a record from filehandle STDIN to $_
print;                       print the current value of $_
chop;                      removes the last character from $_
@things = split;       parses $_ into white-spaces delimited words, which become successive elements of list @things

Subroutines and functions

sub square { return $_[0] ** 2; }
print "5 squared is ", &square(5);                         // Funktionen werden mit '&' angesprochen

Loops

while ( $a < 100 ){
                ...
}
do{
                ...
}  until ( $a > 99 )

for ( $x = 0; $x < 10 ; $x++ ) {
                print "$x\n";
}

Java Servlets

Ein Servlet wird vom Server geladen und initialisiert - init()                 //z.B für DB-Verbindung
Das Servlet brarbeitet eine unbestimte Anzahl Anfragen - service()
Der Server entfernt das Servlet aus dem Server - destroy()                                             //z.b Nach Zeitlimit 30min

import javax.servlet                               // Gernerelles Servlet-API
import javax.servlet.http          // Spezifische API für Servlets, die über das HTTP-Protokoll angesprochen werden
import java.io.* ;

public class SimpleServlet extends HttpServlet
{
 //Handel the HTTP GET method by building a simple web page
 public void doGet (HtttpServletRequest request,                                                //or doPost
                               HTTPServletResponse response)
                      throws ServletException, IOException
 {
  PrintWriter out;
  String title = "Simple Servlet Output";
  //set content type and other response header fields first
  response.setContentType("text/html");
  //out = response.getWriter();                               //für Textdaten,       getOutputStream( ) für binäre Daten
  out.println("<HTML><HEAD><TITLE>");
  out.println(title);
  out.println("</TITLE></HEAD><BODY>");
  out.println("<H1>" + title + "</H1>");
  out.println("<P> This is output from SimpleServlet.");
  out.println("</BODY></HTML>");
  out.close;
 }
}

Session Tracking

public HttpSession getSession(Boolean create);
  doGet (....) ...
{
 //Get the user's session and shopping cart
 HttpSession session = request.getSession(true);
 ShoppingCart cart = (ShoppingCart)session.getAttribute("examples.bookstore.cart");
 //If the user has no cart, create a new one
 (if cart == null)
 {
  cart = new ShoppingCart();
  session.setAttribute("examples.bookstore.cart", cart);
 }
 ...
}

URL-Rewriting

out.println(
  "<a href=\"" +
  response.encodeURL("/servlet/bookdetails?bookId=" + bookId) -+
  "\"> + book.getTitle() + "</a href>
 );

Cookie erstellen

1. Cookie erzeugen
                Cokkie theBook = new Cookie("Buy", bookId);
2. Setzen von Attributen
                theBook.setComment("User wants to buy book" + bookId);
                theBook.setMaxAge(0); // mit 0 wird Cookie auf Client gelöscht, bis Browserfenster geschlossen
3. Cookie versenden
                response.addCookie(getBook);

Cookies auslesen

1. Alle Cookies eines Requests holen
                Cokkie [ ]  cookies = request.getCookies();
2. Anhand von Namen das gewünschte Cookie heraussuchen
                for (int i = 0; i< cookies.length; i++)
                { if (cookies[I].equals("Buy"))... }
3. Wert aus Cookie lesen
                Cookies[i].getValue();

Servlet-Kommunikation

Verwenden von andere Ressourcen auf dem Server
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/bookstore/bookstore.html");
if (dispatcher == null)
 { response.sendError(response.SC_NO_CONTENT); }

Weiterleiten eines Requests

dispatcher.forward(request, response);                             //vollständig
dispatcher.include(request, response);                                //teilweise

Web-Applikationen

Director-Struktur:
/WEB-INF/web.xml                 - Der Deployment descriptor
/WEB-INF/classes/*                - Directory für Servlets und Hilfsklassen
/WEB-INF/lib/*.jar                    - Direcotry für Bibliotheken on Form von Java ARchives

JavaServer Pages (JSP)

<HTML>
<%@ page language= "java" import="java.util.*" %>                                                           // <%@ include file=
<H1>Welcome</H1>
<P>Today is </P>
<jsp: useBean id="clock" scope="session" class="calendar.jspCalendar" />
<%! int a,b; double c; %>       <!--JSP-Deklaration -- >                                                         // <%! Deklaration
<UL>
<LI>Day: <%= clock.getDayOfMonth() %>                                                                          // <%= Expression
<LI>Year: <%= clock.getYear() %>
</UL>
<%-- Check for AM or PM --, JSP Comment %>
<%! int time = Calendar.getInstance.get(Clendar.AM_PM); %>
<% if (time == Calendar.AM) { %>
Good Morning
<% } else { %>
Good Afternoon
<% } %> <%@ include file="copyright.html" %>
</HTML>

Die Page Direktive <% page language=... %> beschreibt Sprache, Imports, Seitentyp
Mit der Include Directive <%@ include file="info.html" %> wird ein File statisch eingebunden.
Mit <jsp:include page="form.jsp" flush="true" /> wird ein File dynamisch eingebunden
Taglibs <@ taglib uri=/tld/service.tld" prefix="menu" %>  erweitert die Menge der Tags.

Objekte

<jsp:useBean id="farbtopf" class="tools.ColorPot" />
<jsp:setProperty name="farbtopf" property="color" value="blue" />                   //ruft  farbtop.setColor("blue") auf

Weiterleiten eines Client-Requests <jsp:forward page="sorry.jsp" />

Tag Libraries für JSP

Tag Libraries mussen im Tag Library Descriptor File .tld eingetragen werden.                  // taglib.tld

javax.servlet.jsp.tagext.Tag                                  Tag Handler
javax.servlet.jsp.tagext.TagSupport                     ohne Body
javax.servlet.jsp.tagext.BodyTagSupport             mit Body
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class HelloTag implements Tag
{
 private PageContext pageContext;
 private Tag parent ;
 public HelloTag( )
 { super( ) }

 public void setPageContext(final PageContext pageContext)
 {this.pageContext = pageContext; }

 public void setParent(final Tag parent)
 { this.parent=parent; }

public Tag getParent
 { return parent; }

public int doStartTag( ) throws JspTagException
 { return SKIP_BODY; }          // oder EVAL_BODY_INCLUDE

public int doEndTag( ) throws JspTagException
 {
  try
 { pageContext.getOut.write("Hello, Tag!") }
 catch(IOException e)
 { throw new JspTagException("IO Error: " + e.getMessage( ) ); }
return EVAL_PAGE;              // oder SKIP_PAGE
}
 public void release( ) { }        //Ressourcen freigeben
}

Verwendung

<%@ taglib uri="ttl" prefix"ttl" %>
<ttl: HelloTag />

JSP-ErrorPages

<@ page isErrorPage="true" %>
<%= exception.toString( ) %>                               //Implizit Object

XML (Extensible Markup Language)

XML ermöglich plattformenabhängigen Datenaustausch, dank Unicode sprachunabhängig.
XML ist eine low-level-Systax zur Darstellung strukturierter Daten.
Ein Dokument besteht aus Deklaration, Kommentaren, Root-Element, verschachtelten Elementen und Element Attributen.

<?xml version='1.0' encoding="ISO-8859-1" standalone="yes" ?>                      //declaration
<!--XML comment -->
<!DOCTYPE slideshow SYSTEM "slideshow.dtd" [
                <! ENTITY product "WonderWidget">
                <! ENTITY copyright SYSTEM "copyright.xml"> ]>
<slideshow title="&product; Slide Show"                                                                            //root element
                   author = "Truly yours" >
                <?my.presentation.Program: QUERY="exec,tech,all"?>                       //?target instructions?>
                <slide type="all">                                                                                  //XML element
                              <title> Wake up! </title>
                              <item>&copyright;</item>                                                      //Reference
                </slide>
</slideshow>

vordefinierte Character-Entities:            > = &gt, < = &lt, ä = &auml; & = &amp

Document Type Definition (DTD)

wird zur Validierung der Dokument-Sturktur verwendet

<!ELEMENT slideshow (silde+)>                            // slideshow contains 1 to n slide element
<!ELEMENT slide (title, item*)>

XHTML

anstelle von HTML-Tags XML-Tags, eine XML-Anwendung

XHTML Transitional                muss "well-formed"/ "valid"  sein
XHTML Strict                          keine Format-bezogenen Tags, nur CSS
XHTML Frameset                    für Framesets

SAX        Simple API for XML

serieller Zugriff, Event-gesteuertes Protokoll, neuer Tag löst Callback-Handler aus.

DOM       Document Object Model

View eines Dokuments, Sammlung von Objekten, dynamisch zugreifen und manipulieren, random access mode
Elemente hinzufügen, verändern oder löschen
Fehlermeldungen über Rückgabewerte

JAXP      Java APIs for XML Processing

SAX
import org.xml.sax.*;
import org.xml.sax.helpers.Defaulhandler;
import javax.xml.parsers.*;

public class SAXEcho extends DefaultHandler
{ ... }
public static void main(Sting[ ] args)
{
 DefaultHandler handler = new SAXEcho();
 SAXParserFactory factory = SAXParserFactory.newInstance( );
 try{
  SAXParser saxParser = factory.newSAXParser( );
  saxPArser.parse( new File(args[0], handler);
} catch (Exception e) { ...}

public void startDocument() throws SAXException {..}
public void endDocument() throws SAXException {..}
public void startElement (...)
public void endElement (...)
public void characters(...)

---------

DOM

import org.w3c.dom.*;
DocumentBuilder builder = factory.newDocumentBuilder( );
document = builder.parse( new File(argv[0]) );
document.getDocumentElement().normalize( );     //compact Document
XmlDocument xdoc = (XMLDocument) document;
xdoc.write(System.out);

EJB Enterprise JavaBeans

J2EE Java 2 Enterprise Edition

Framework für Serverapplikation
Architektur:             Browser, Application Server, Enterprise Information Systems (EIS)
Domain-Klassen:
  conversionals state              exisitert eine gewisse Zeit
  persistent state                    permanent

session beans        // private Ressourcen eines einzelnen Clients

Home Interface       = erstellen, löschen, auffinden, zugreifen            // Eine Implementation, in JNDI eintragen
Remote Interface    = Public methoden, extends EJBObject                 // Eine Implementation pro EJB

zurück zu Java and Internet part 1 <--  --> zur Java Übersicht