Servlet II Anwendungen • • • • • Formular Auswertung Zähler Zähler mit Zwischenspeicherung Hintergrund Berechnung Passwort Abfrage Auswertung eines Formulars http://www.sdf.... Get Request Webserver e index.html ons Resp Servlet Container Post Request s Respon e processformular 1 <FORM> <form method="POST" action="processformular"> <input type="text" name=name size=50 > <input type="submit" > </form> HTML http Request get HTML Formular Servlet Auswertung doGet(… <form method=“GET" post <form method="POST" doPost(… Formular erstellen 2 Auswertung package counter; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class formular extends HttpServlet { private static final String CONTENT_TYPE = "text/html"; public void init() throws ServletException { } public void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { response.setContentType(CONTENT_TYPE); PrintWriter out = response.getWriter(); String name = req.getParameter("name"); String s1 = req.getParameter("is-gift"); String s2 = req.getParameter("address-line-1"); String s3 = req.getParameter("address-line-2"); String s4 = req.getParameter("city"); Auswertung String s5 = req.getParameter("state"); String s6 = req.getParameter("country"); String s7 = req.getParameter("phone-number"); String s8 = req.getParameter("shipping-billing"); out.println("<HTML>"); out.println("<HEAD><TITLE>Formular</TITLE></HEAD>"); out.println("<BODY>"); out.println("Name: " + name +"<BR>"); out.println("Geschenk: " + s1 +"<BR>"); out.println("Adr: " + s2 +"<BR>"); out.println("Adr2: " + s3 +"<BR>"); out.println("Stadt: " + s4 +"<BR>"); out.println("Land: " + s6 +"<BR>"); out.println("Tel: " + s7 +"<BR>"); out.println("Rechnung: " + s8 +"<BR>"); out.println("</BODY></HTML>"); } public void destroy() {} } 3 Simple Counter package counter; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SimpleCounter extends HttpServlet { int count = 0; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); count++; out.println("Since loading, this servlet has been accessed " + count + " times."); } } Internet Å Mehrfach Anfragen 4 Daten Inkonsistenz Kein Problem bei lokalen Variablen Vorsicht bei Instanz Variablen Bsp: Simple Counter count++; // Thread 1 count++; // Thread 2 out.println("Since loading, ….. // Thread 1 out.println("Since loading, ….. // Thread 2 Hilfe: synchronized Blocks: Nur ein einzelner Thread darf einen synchronized Block ausführen Simple Counter synchronized package counter; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SimpleCounter extends HttpServlet { int count = 0; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); synchronized(this) { count++; out.println("Since loading, this servlet has been accessed "+count +" times."); } } } 5 Counter II package counter; import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class HolisticCounter extends HttpServlet { static int classCount = 0; // verteilt auf alle Instanzen int count = 0; // Nur für dieses Servlet static Hashtable instances = new Hashtable(); // verteilt auf alle Instanzen public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); count++; out.println("Since loading, this servlet instance has been accessed " + count + " times."); Counter II // Trick: Die Instanzen werden gezählt, indem sie in eine // Hashtable eingetragen werden. Gleiche Einträge werden ignoriert. // Die size() Methode liefert die Zahl der einzelnen Instanzen. instances.put(this, this); out.println("There are currently " + instances.size() + " instances."); classCount++; out.println("Across all instances, this servlet class has been " + "accessed " + classCount + " times."); } } 6 Lebenszyklus • Initialisierung • Antworten auf Anfragen • Zerstörung • Å Persistenz DB Verbindung Information von früheren Transaktionen Counter III package counter; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class InitDestroyCounter extends HttpServlet { int count; public void init() throws ServletException { // Versuch den gespeicherten Zustand des Zählers zu laden FileReader fileReader = null; BufferedReader bufferedReader = null; try { fileReader = new FileReader("InitDestroyCounter.initial"); bufferedReader = new BufferedReader(fileReader); String initial = bufferedReader.readLine(); count = Integer.parseInt(initial); return; } 7 InitDestroyCounter catch (FileNotFoundException ignored) { } catch (IOException ignored) { } catch (NumberFormatException ignored) { } finally { // kein gespeicherter Zähler // Problem beim lesen // Korruptes File // Schliessen des Files try { if (bufferedReader != null) {bufferedReader.close(); } } catch (IOException ignored) { } } // Überprüfe ob ein Initialisierungsparameter vorhanden ist. String initial = getInitParameter("initial"); try { count = Integer.parseInt(initial); return; } catch (NumberFormatException ignored) { } // null or non-integer value // Default 0 count = 0; } InitDestroyCounter public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); count++; out.println("Since the beginning, this servlet has been accessed " + count + " times."); } public void destroy() { super.destroy(); saveState(); } 8 InitDestroyCounter public void saveState() { // Versuch den Counter zu speichern FileWriter fileWriter = null; PrintWriter printWriter = null; try { fileWriter = new FileWriter("InitDestroyCounter.initial"); printWriter = new PrintWriter(fileWriter); printWriter.println(count); return; } catch (IOException e) { // Problem beim Schreiben } finally { // Zur Sicherheit das File schliessen if (printWriter != null) { printWriter.close(); } } } } PrimSearcher package counter; import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class PrimeSearcher extends HttpServlet implements Runnable { long lastprime = 0; // letzte gefundene Primzahl Date lastprimeModified = new Date(); // Zeit Thread searcher; // Hintergrund Thread public void init() throws ServletException { searcher = new Thread(this); searcher.setPriority(Thread.MIN_PRIORITY); searcher.start(); } http://www.mindview.net/Books/DownloadSites/ 9 PrimSearcher public void run() { long candidate = 1000000000000001L; while (true) { if (isPrime(candidate)) { lastprime = candidate; // aktuelle Primzahl lastprimeModified = new Date(); // Zeit der letzten gefunden Primzahl } candidate += 2; // keine geraden Primzahlen try { searcher.sleep(200); // an andere Prozesse denken } catch (InterruptedException ignored) { } } PrimSearcher private static boolean isPrime(long candidate) { // Dividiere die Zahl durch alle ungeraden Zahlen zwischen 3 und sqrt(z) long sqrt = (long) Math.sqrt(candidate); for (long i = 3; i <= sqrt; i += 2) { if (candidate % i == 0) return false; // Ein Faktor gefunden } return true; //kein Faktor } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); if (lastprime == 0) { out.println("Still searching for first prime..."); } else { out.println("The last prime discovered was " + lastprime); out.println(" at " + lastprimeModified); } } public void destroy() { searcher.stop();} } http://archive.coreservlets.com/ 10 Protected Page package protectedpage; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.Properties; import sun.misc.BASE64Decoder; public class ProtectedPage extends HttpServlet { private Properties passwords; private String passwordFile; public void init(ServletConfig config) throws ServletException { super.init(config); try { passwordFile = config.getInitParameter("passwordFile"); passwords = new Properties(); passwords.load(new FileInputStream(passwordFile)); } catch(IOException ioe) {} } Protected Page public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String authorization = request.getHeader("Authorization"); if (authorization == null) { askForPassword(response); } else { 11 Protected Page String userInfo = authorization.substring(6).trim(); BASE64Decoder decoder = new BASE64Decoder(); String nameAndPassword = new String(decoder.decodeBuffer(userInfo)); int index = nameAndPassword.indexOf(":"); String user = nameAndPassword.substring(0, index); String password = nameAndPassword.substring(index+1); String realPassword = passwords.getProperty(user); if ((realPassword != null) && (realPassword.equals(password))) { String title = "Welcome to the Protected Page"; out.println(ServletUtilities.headWithTitle(title) + Protected Page "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=CENTER>" + title + "</H1>\n" + "Congratulations. You have accessed a\n" + "highly proprietary company document.\n" + "Shred or eat all hardcopies before\n" + "going to bed tonight.\n" + "</BODY></HTML>"); } else { askForPassword(response); } } } 12 Protected Page private void askForPassword(HttpServletResponse response) { response.setStatus(response.SC_UNAUTHORIZED); // Ie 401 response.setHeader("WWW-Authenticate", "BASIC realm=\"privileged-few\""); } /** Handle GET and POST identically. */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } Praktikum Kundenangaben mit PW Abfrage: 1. http Passwortabfrage 2. Formular mit Passwortabfrage 3. Alle Adressen im Container werden angezeigt. 4. Formular zur Eingabe von weiteren Adressen (5.) Save & Edit & Delete 13 Ihr Job 1.) 3.) alle Daten anzeigen 2.) 4.) Eingabe 1.) Neues Projekt 14 2.) HTML Files in Projekt Ordner kopieren und hinzufügen 15 3. Neues Servlet oder Webanwendung erzeugen HTML Files zur Webanwendung hinzufügen 16 web.xml File anpassen Servlet Class-File Angaben 17 Servlet Mapping Angaben 18