1 / 94

Servlets chapt4

Servlets chapt4. Information retrieval. Handling requests. To build a successful webapp you probably need to know about The server that will be running your servlets And the environment (eg., O.S., hardware, etc.) Specifics about the client and the nature of the requests.

Download Presentation

Servlets chapt4

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. Servlets chapt4 Information retrieval

  2. Handling requests • To build a successful webapp you probably need to know about • The server that will be running your servlets • And the environment (eg., O.S., hardware, etc.) • Specifics about the client and the nature of the requests

  3. Methods providing servlets with information • These methods improve on the CGI environment variables by allowing stronger type-checking. • CGI has delays caused by the need to pre-calculate environment variables whether they are used or not. • A CGI program acts independently of the server, once it is launched. Only standard output is available to the program. • A servlet may be inside the server, or a connected process and so can make ad hoc requests for information from the server.

  4. Type checking comparison, perl, C and java • Perl checks a port number with code like $port =$ENV(‘SERVER_PORT’); Where $port is untyped. • A CGI program in C uses, char *port=getenv(“SERVER_PORT”); The chance of an accidental error is high, for example if the environment variable is misspelled, or a datatype mismatch. • Java code is int port =req.getServerPort(); And the compiler can insure no spelling errors and correct datatyping.

  5. Text table shows how servlet functions map to environment variables. Table in text pg 73

  6. Partial table

  7. Init parameters • Init parameters may be associated with specific servlets by name and are set in web.xml and may be used in init() to set initial values or customize behavior. • A servlet uses getInitialParameter() method to access its initial parameters: public String ServletConfig. getInitialParameter(String name) This method returns the value of the named parameter or null if it doesn’t exist. Since GenericServlet implements ServletConfig interface, it can call the method directly. Initial parameters could be used to identify details of a database connection for a servlet. (like port, host, db, user, password, proxy)

  8. Init parameters import java.io.*; import java.util.*; import javax.servlet.*; public class InitSnoop extends GenericServlet { // No init() method needed public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); out.println("Init Parameters:"); Enumeration list = getInitParameterNames(); while (list.hasMoreElements()) { String name = (String) list.nextElement(); out.println(name + ": " + getInitParameter(name)); } } }

  9. Servlet tag in web.xml <servlet> <servlet-name>InitSnoop</servlet-name> <description> A simple servlet that looks for its init parameters. </description> <servlet-class> InitSnoop </servlet-class> <init-param> <param-name>initialguy </param-name> <param-value>12345</param-value> </init-param> </servlet>

  10. Screenshot of tomcat/initsnoop

  11. ServerSnoop import java.io.*; import java.util.*; import javax.servlet.*; public class ServerSnoop extends GenericServlet { public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); ServletContext context = getServletContext(); out.println("req.getServerName(): " + req.getServerName()); out.println("req.getServerPort(): " + req.getServerPort()); out.println("context.getServerInfo(): " + context.getServerInfo()); out.println("getServerInfo() name: " + getServerInfoName(context.getServerInfo())); out.println("getServerInfo() version: " + getServerInfoVersion(context.getServerInfo())); out.println("context.getAttributeNames():"); Enumeration list = context.getAttributeNames(); while (list.hasMoreElements()) { String name = (String) list.nextElement(); out.println(" context.getAttribute(\"" + name + "\"): " + context.getAttribute(name)); } }

  12. ServerSnoop slide2 private String getServerInfoName(String serverInfo) { int slash = serverInfo.indexOf('/'); if (slash == -1) return serverInfo; else return serverInfo.substring(0, slash); } private String getServerInfoVersion(String serverInfo) { // Version info is everything between the slash and the space int slash = serverInfo.indexOf('/'); if (slash == -1) return null; int space = serverInfo.indexOf(' ', slash); if (space == -1) space = serverInfo.length(); return serverInfo.substring(slash + 1, space); } }

  13. ServerSnoop servlet on Tomcat

  14. Creating a temp file using servletcontext • Each servlet context gets its own working (temp) directory which is mapped by the attribute javax.servlet.context.tempdir //get directory File dir=(File)getServletContext().getAttribute(“javax.servlet.context.tempdir”); //create a file File f=File.createTempFile(“xxx”,”.tmp”,dir); //get ready to write to it FileOutputStream fout=new FileOutputStream(f);

  15. Here’s the entire WriteToFile servlet import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class WriteToFile extends GenericServlet { public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { File dir=(File)getServletContext().getAttribute("javax.servlet.context.tempdir"); File f=File.createTempFile("xxx",".tmp",dir); FileOutputStream fout=new FileOutputStream(f); //now write stuff to file //and don’t forget to close the file fout.close(); } public String getServletInfo() { return "A servlet that writes to a file in work/ dir"; } }

  16. Running WriteToFile servlet: note file path

  17. WriteToFile servlet output to client

  18. File Location- note URL

  19. Get a file’s location import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class FileLocation extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); if (req.getPathInfo() != null) { out.println("The file \"" + req.getPathInfo() + "\""); out.println("Is stored at \"" + req.getPathTranslated() + "\""); } else { out.println("Path info is null, no file to lookup"); } } }

  20. http://localhost:8080/myservlets/FileLocation/pathinfo/morepathinfo/Hello.txthttp://localhost:8080/myservlets/FileLocation/pathinfo/morepathinfo/Hello.txt

  21. Putting a few tricks together • An init parameter called key can be used to see if a servlet should be run on a particular server. The key might “fit” the server’s IP and port information for example. • The KeyedServerLock servlet uses these tricks.

  22. KeyedServerLock – obviously my version is pirated

  23. KeyedServerLock import java.io.*; import java.net.*; import java.util.*; import javax.servlet.*; public class KeyedServerLock extends GenericServlet { // This servlet has no class or instance variables // associated with the locking, so as to simplify // synchronization issues. public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); // The piracy check shouldn't be done in init // because name/port are part of request. String key = getInitParameter("key"); String host = req.getServerName(); int port = req.getServerPort();

  24. KeyedServerLock // Check if the init parameter "key" unlocks this server. if (! keyFitsServer(key, host, port)) { // Explain, condemn, threaten, etc. out.println("Pirated!"); } else { // Give 'em the goods out.println("Valid"); // etc... } } // This method contains the algorithm used to match a key with // a server host and port. This example implementation is extremely // weak and should not be used by commercial sites. // private boolean keyFitsServer(String key, String host, int port) { if (key == null) return false; long numericKey = 0; try { numericKey = Long.parseLong(key); } catch (NumberFormatException e) { return false; }

  25. KeyedServerLock // The key must be a 64-bit number equal to the logical not (~) // of the 32-bit IP address concatenated with the 32-bit port number. byte hostIP[]; try { hostIP = InetAddress.getByName(host).getAddress(); } catch (UnknownHostException e) { return false; } // Get the 32-bit IP address long servercode = 0; for (int i = 0; i < 4; i++) { servercode <<= 8; servercode |= hostIP[i]; } // Concatentate the 32-bit port number servercode <<= 32; servercode |= port; // Logical not long accesscode = ~numericKey; // The moment of truth: Does the key match? return (servercode == accesscode); } }

  26. KeyedServerUnlock is the companion for KeyedServerLock –get the key

  27. Init param holds key… I got the key from the keyedserverunlock servlet <servlet> <servlet-name> KeyedServerLock </servlet-name> <servlet-class> KeyedServerLock </servlet-class> <init-param> <param-name>key </param-name> <param-value> 9151314447111823249 </param-value> <description> The key value to unlock the servlet's functionality </description> </init-param> </servlet>

  28. Using serverlock and serverunlock together: Not sure why keys are off by one!!!

  29. Valid…subtracted one before compare

  30. Code from serverlock long servercode = 0; for (int i = 0; i < 4; i++) { servercode <<= 8; servercode |= hostIP[i]; } // Concatentate the 32-bit port number servercode <<= 32; servercode |= port; • Code from serverunlock long servercode = 0; for (int i = 0; i < 4; i++) { servercode <<= 8; servercode |= hostIP[i]; } // Concatentate the 32-bit port number servercode <<= 32; servercode |= port; // The key is the logical not return ~servercode;

  31. Getting info about the client machine • ServletRequest methods getRemoteAddr() and getRemoteHost() both return strings and can be used to get some info about the client machine. • The client IP or remote host name can further be converted into a java InetAddress using its method getByName() • The next example considers whether we should allow access to restricted material based on the country from which the request comes.

  32. Getting client information: is this client allowed to download? public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); // ...Some introductory HTML...then Get the client's hostname String remoteHost = req.getRemoteHost(); // See if the client is allowed if (! isHostAllowed(remoteHost)) { out.println("Access <BLINK>denied</BLINK>"); } else { out.println("Access granted"); // Display download links, etc... } } // Disallow hosts ending with .cu, .ir, .iq, .kp, .ly, .sy, and .sd. private boolean isHostAllowed(String host) { return (!host.endsWith(".cu") && !host.endsWith(".ir") && !host.endsWith(".iq") && !host.endsWith(".kp") && !host.endsWith(".ly") && !host.endsWith(".sy") && !host.endsWith(".sd")); }

  33. Getting client information

  34. Personalized Welcome servlet • Uses req.getRemoteUser() with a hashtable to keep track of multiple visits in order to greet a user by name. • (I think) in order to send a greeting other than “welcome” this needs to be combined with the server requiring a name/pw to access the resource

  35. Personalized Welcome servlet (doGet()) String remoteUser = req.getRemoteUser(); if (remoteUser == null) { out.println("Welcome!"); } else { out.println("Welcome, " + remoteUser + "!"); Date lastAccess = (Date) accesses.get(remoteUser); if (lastAccess == null) { out.println("This is your first visit!"); } else { out.println("Your last visit was " + accesses.get(remoteUser)); } if (remoteUser.equals("PROFESSOR FALKEN")) { out.println("Shall we play a game?"); } accesses.put(remoteUser, new Date()); }

  36. Getting user information

  37. Getting parameters

  38. Getting parameters • <FORM Method=GET Action="http://localhost:8080/servlet/ParameterSnoop"> • a parameter <input type=text name="word"> • another parameter <input type=text name="value"> • an another <input type=text name="thing"> • <input type =submit> • </form>

  39. Parameters, continued

  40. ParameterSnoop.java public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); out.println("Query String:"); out.println(req.getQueryString()); out.println(); out.println("Request Parameters:"); Enumeration enum = req.getParameterNames(); while (enum.hasMoreElements()) { String name = (String) enum.nextElement(); String values[] = req.getParameterValues(name); if (values != null) { for (int i = 0; i < values.length; i++) { out.println(name + " (" + i + "): " + values[i]); } } } }

  41. More values of same parameters

  42. With more values of parameters

  43. The Form revised <FORM Method=GET Action="http://localhost:8080/servlet/ParameterSnoop"> a parameter <input type=text name="word"><p> same parameter <input type=text name="word"> <p>same again <input type=text name="word"><p> another parameter <input type=text name="value"> <p> and same parameter <input type=text name="value"> a final <input type=text name="thing"> <input type =submit> </form>

  44. What happens to ‘&’ if entered as a parameter?

  45. Seems to know what to do with them

  46. Uploading a file

  47. form • <FORM Method=Post • ACTION="http://csci345.oneonta.edu:8080/myexamples/UploadTest" • ENCTYPE="multipart/form-data"> • Name? <input type=text name=submitter><br> • what file? <input type=file name=file><br> • <input type=submit> • </form>

  48. form in IE after browse and select

  49. UploadTest.java public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); try { // Blindly take it on faith this is a multipart/form-data request // Construct a MultipartRequest to help read the information. // Pass in the request, a directory to save files to, and the // maximum POST size we should attempt to handle. // Here we (rudely) write to the server root and impose 5 Meg limit. MultipartRequest multi = new MultipartRequest(req, ".", 5 * 1024 * 1024); out.println("<HTML>"); out.println("<HEAD><TITLE>UploadTest</TITLE></HEAD>"); out.println("<BODY>"); out.println("<H1>UploadTest</H1>"); // Print the parameters we received out.println("<H3>Params:</H3>"); out.println("<PRE>"); Enumeration params = multi.getParameterNames(); while (params.hasMoreElements()) { String name = (String)params.nextElement(); String value = multi.getParameter(name); out.println(name + " = " + value); } out.println("</PRE>");

  50. UploadTest.java // Show which files we received out.println("<H3>Files:</H3>"); out.println("<PRE>"); Enumeration files = multi.getFileNames(); while (files.hasMoreElements()) { String name = (String)files.nextElement(); String filename = multi.getFilesystemName(name); String type = multi.getContentType(name); File f = multi.getFile(name); out.println("name: " + name); out.println("filename: " + filename); out.println("type: " + type); if (f != null) { out.println("length: " + f.length()); } out.println(); } out.println("</PRE>"); } catch (Exception e) { out.println("<PRE>"); e.printStackTrace(out); out.println("</PRE>"); } out.println("</BODY></HTML>"); }

More Related