zurück zu java and internet part 1 <--- ---> zur Java Übersicht
<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
<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>
<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();">
break
false
in
this void
continue
for
new
true while
delete function
null
typeof with
else
if
return var
Number String boolean Function Object
Array null undefined
var a = new Object(); |
Assoziativarray |
s1 = a.join // join wandelt alle
Elemente in Strings um
// reverse kehr den Inhalt eines Arrays um
//sort , sortiert Alphabetisch
if( boolean) for(initialize; test; action) for(variable in object) |
break with(object) function funcname([arg_1 [, arg_n]]) return [ expression] |
Link
onClick()
onMouseOut() onMouseOver()
Button
onBlur()
onClick()
onFocus()
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
ServerType standalone |
<VirtualHost www.hello.com> |
#!/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
('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)
@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, ...)
$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.
$pet = "I love my cat.\n";
$pet =~ s/cat/dog/;
print $pet;
$_,$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
sub square { return $_[0] ** 2; }
print
"5 squared is ",
&square(5);
// Funktionen werden mit '&' angesprochen
while ( $a < 100 ){
...
}
do{
...
} until ( $a > 99 )
for ( $x = 0; $x < 10 ; $x++ ) {
print "$x\n";
}
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;
}
}
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);
}
...
}
out.println(
"<a href=\"" +
response.encodeURL("/servlet/bookdetails?bookId=" + bookId)
-+
"\"> + book.getTitle() + "</a href>
);
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);
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();
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
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
<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.
<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 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
}
<%@ taglib uri="ttl" prefix"ttl" %>
<ttl: HelloTag />
<@ page isErrorPage="true" %>
<%=
exception.toString( )
%>
//Implizit Object
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>©right;</item>
//Reference
</slide>
</slideshow>
vordefinierte Character-Entities: > = >, < = <, ä = ä & = &
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*)>
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
serieller Zugriff, Event-gesteuertes Protokoll, neuer Tag löst Callback-Handler aus.
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
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(...)
---------
DOMimport
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);
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