1 / 36

Servlet II

Servlet II. Anwendungen Formular Auswertung Zähler Zähler mit Zwischenspeicherung Hintergrund Berechnung Passwort Abfrage. Get Request. Response. Post Request. Response. Auswertung eines Formulars. http://www.sdf. Webserver index.html. Servlet Container processformular. <FORM>.

lise
Download Presentation

Servlet II

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. Servlet II • Anwendungen • Formular Auswertung • Zähler • Zähler mit Zwischenspeicherung • Hintergrund Berechnung • Passwort Abfrage

  2. Get Request Response Post Request Response Auswertung eines Formulars http://www.sdf.... Webserver index.html Servlet Container processformular

  3. <FORM> • <form method="POST" action="processformular"> • <input type="text" name=name size=50 > • <input type="submit" > • </form> HTML

  4. Formular erstellen

  5. 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");

  6. 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() {} • }

  7. 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."); • } • }

  8. Internet  Mehrfach Anfragen

  9. 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

  10. 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."); • } • } • }

  11. 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.");

  12. 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."); • } • }

  13. Lebenszyklus • Initialisierung • Antworten auf Anfragen • Zerstörung •  Persistenz • DB Verbindung • Information von früheren Transaktionen

  14. 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; • }

  15. InitDestroyCounter • catch (FileNotFoundException ignored) { } // kein gespeicherter Zähler • catch (IOException ignored) { } // Problem beim lesen • catch (NumberFormatException ignored) { } // Korruptes File • finally { • // 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; • }

  16. 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(); • }

  17. 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(); • } • } • } • }

  18. 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/

  19. 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) { } • }

  20. 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/

  21. 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) {} • }

  22. 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 {

  23. 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) +

  24. 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); • } • } • }

  25. 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); • } • }

  26. Praktikum • Kundenangaben mit PW Abfrage: • http Passwortabfrage • Formular mit Passwortabfrage • Alle Adressen im Container werden angezeigt. • Formular zur Eingabe von weiteren Adressen • (5.) Save & Edit & Delete

  27. Ihr Job • 1.) • 3.) alle Daten anzeigen • 4.) Eingabe • 2.)

  28. 1.) Neues Projekt

  29. 2.) HTML Files in Projekt Ordner kopieren und hinzufügen

  30. 3. Neues Servlet oder Webanwendung erzeugen

  31. HTML Files zur Webanwendung hinzufügen

  32. web.xml File anpassen

  33. Servlet Class-File Angaben

  34. Servlet Mapping Angaben

More Related