html5-img
1 / 84

Web Application Development

Web Application Development. Outline. Web application architecture HTTP CGI Java Servlets Apache Tomcat Session maintenance. Architecture. HTTP. Created by Tim Berners-Lee at CERN Defined 1989-1991 Standardized and much expanded by the IETF Rides on top of TCP protocol

jfagan
Télécharger la présentation

Web Application Development

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. Web Application Development

  2. Outline • Web application architecture • HTTP • CGI • Java Servlets • Apache Tomcat • Session maintenance

  3. Architecture

  4. HTTP • Created by Tim Berners-Lee at CERN • Defined 1989-1991 • Standardized and much expanded by the IETF • Rides on top of TCP protocol • TCP provides: reliable, bi-directional, in-order byte stream • Goal: transfer objects between systems • Do not confuse with other WWW concepts: • HTTP is not page layout language (that is HTML) • HTTP is not object naming scheme (that is URLs) • Text-based protocol • Human readable

  5. Client-Server Paradigm Client: • initiates contact with server (“speaks first”) • typically requests service from server, • for Web, client is implemented in browser; for e-mail, in mail reader Server: • provides requested service to client • e.g., Web server sends requested Web page, mail server delivers e-mail HTTP request PC running Explorer HTTP response Apache Web server http request http response Mac running Safari

  6. HTTP

  7. HTTP Request Message Format HTTP method sp sp HTTP version cr request line URL lf cr lf header field name : field value … header lines cr lf header field name : field value cr lf Entity Body

  8. HTTP Request Example request line (GET, POST, HEAD commands) GET /somedir/page.html HTTP/1.0 User-agent: Mozilla/4.0 Accept: text/html, image/gif,image/jpeg Accept-language:fr (extra carriage return, line feed) header lines Carriage return, line feed indicates end of message

  9. HTTP Response Message Format HTTP version sp sp status phrase cr response line status code lf cr lf header field name : field value … header lines cr lf header field name : field value cr lf Response Body

  10. HTTP Response Example status line: (protocol status code status phrase) HTTP/1.0 200 OK Date: Thu, 25 Aug 2001 12:00:15 GMT Server: Apache/1.3.0 (Unix) Last-Modified: Mon, 22 Aug 2001 …... Content-Length: 6821 Content-Type: text/html data data data data data ... data data data data data ... data data data data data ... header lines Carriage return, line feed indicates end of message data, e.g., requested html file

  11. CGI Architecture

  12. Objectives • Standardizes execution of server-side applications/handlers • Specifies: • Interface between client and handler • Interface between web server and hander

  13. Web Server-Handler Interaction • Handler Input • Meta-variables • Stdin (message body) • Handler Output • Stdout

  14. Client-Handler Interaction • Clients request the execution of a handler program by means of a: • A request method (e.g., GET, POST) • Universal Resource Identifier (URI) • Identifies handler • Extra arguments

  15. URI Syntax <protocol>://<host><port>/<path-info><script>"?"<query-string> http://finance.yahoo.com/add?op1=10&op2=20 <protocol> http <host> finance.yahoo.com <port> 80 <path-info> null <script> add <query-string> op1=10, op2=20

  16. Query String Encoding • RFC 2396 • Why encode? • Can think of a CGI script as a function, send arguments by specifying name/value pairs. • Way to pack and unpack multiple arguments into a single string

  17. Encoding Rules • Allarguments • Single string of ampersand (&) separated name=value pairs name_1=value_1&name_2=value_2&... • Spaces • Replaced by a plus (+) sign • Other characters (ie, =, &, +) • Replaced by a percent sign (%) followed by the two-digit hexadecimal ASCII equivalent

  18. Method • GET • Arguments appear in the URL after the ? • Can be expressed as a URL • Limited amount of information can be passed this way • URL may have a length restriction on the server • Arguments appear on server log • POST • Arguments are sent in the HTTP message body • Cannot be expressed as URL • Arbitrarily long form data can be communicated (some browsers may have limits (i.e. 7KB)). • Arguments usually does not appear in server logs.

  19. Forms and CGI • Specify request method in “method” attribute • Automatically encodes all named field values

  20. Example: add.html

  21. Servlets • Generic Java2EE API for invoking and connecting to “mini-servers” (lightweight, short-lived, server-side interactions). • Mostly HTTPServlets • Generate HTTP responses (as for CGI) • Servlet code snippets can be embedded directly into HTML pages: JSP = Java Server Pages • Competitor: Microsoft ASP = Active Server Pages

  22. Servlet Architecture • Web server: Apache, Netscape Enterprise, IIS • Servlet container: Running JVM, hooked into the web server, loads and maintains servlets, session info, object store • Servlet: A Java class used to handle a specific request.

  23. Java Servlet-Based Web Server Main Process JVM Request for Servlet1 Thread Servlet1 Request for Setvlet2 Thread Servlet2 Thread Request for Servlet1

  24. Servlet API (javax.Servlet) • Servlet Container • Servlet Interface • HttpServletResponce • HttpServletRequest • ServletContext

  25. Servlet Container • Contains and manages servlets through their lifecycle • Provides the network services over which requests and responses are sent • Decodes requests • Formats MIME based responses

  26. Servlet Interface • Central abstraction of the servlet API • All servlets either implement this interface, or extend a class that implements this interface • GenericServlet and HttpServlet two classes in the servlet API that implement the Servlet interface

  27. HttpServlet • Web developers extend HttpServlet to implement their servlets. • Inherited from GenericServlet • Init() • Destroy() • Defined by HTTPServlet • doGet() • doPost()

  28. doGet() and doPost() protected void doGet(HttpServletRequest req, HttpServletResponse resp) protected void doPost(HttpServletRequest req, HttpServletResponse resp)

  29. HttpServletResponse • Encapsulates all information to be returned from the server to the client • In the HTTP protocol, this information is transmitted from the server to the client either by HTTP headers or the message body of the request. • Headers: Can set/manipulate http headers • primitive manipulation: setStatus(), setHeader(), addHeader() • convenience methods: setContentType(), sendRedirect(), sendError() • Body:Obtain a PrintWriter, used to return character data to the client • getWriter()

  30. Example: Hello World

  31. HttpServletRequest • Encapsulates all information from the client request • In the HTTP protocol, this information is transmitted from the client to the server in the HTTP headers and the message body of the request. • Manipulate 'form' variables: getParameter() getParameterNames() getParameterValues()

  32. Example: Form

  33. Environment Variables DOCUMENT_ROOT root directory of your server HTTP_COOKIE visitor's cookie, if one is set HTTP_HOST hostname of the page HTTP_REFERER HTTP_USER_AGENT browser type of the visitor HTTPS "on" if called through a secure server QUERY_STRING query string REMOTE_ADDR IP address of the visitor REMOTE_HOST hostname of the visitor REMOTE_USER visitor's username REQUEST_METHOD GET or POST REQUEST_URI SCRIPT_FILENAME The full pathname of the current CGI SERVER_SOFTWARE server software (e.g. Apache 1.3)

  34. Example: Environment Variables

  35. Tomcat Configuration Tomcat webapps conf csc309Servlets Root server.xml web.xml index.html index.jsp WEB-INF tomcat_users.xml web.xml classes HelloWorld.class SomeOther.class

  36. Deployment Descriptor (web.xml) • $CATALINA_HOME/conf/web.xml • Default for all web applications • $CATALINA_HOME/webapp/ece1779Servlets/WEB_INF/web.xml • Specific to ece779Servlets <servlet> <servlet-name>SampleServerName</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>SampleServletName</servlet-name> <url-pattern>/index.html</url-pattern> </servlet-mapping> http://127.0.0.1:8080/ece1779Servlets/index.html Maps to: $CATALINA_HOME/webapp/ece1779Servlets/WEB_INF/classes/HelloWorld.class

  37. $CATALINA_HOME/conf/tomcat_users.xml <?xml version='1.0' encoding='utf-8'?> <tomcat-users> <role rolename="tomcat"/> <role rolename="role1"/> <role rolename="manager"/> <role rolename="admin"/> <user username= “ece1779" password= “secret" fullName= "name"roles="admin,manager"/> <user username="tomcat" password="tomcat" roles="tomcat"/> <user username="role1" password="tomcat" roles="role1"/> <user username="both" password="tomcat" roles="tomcat,role1"/> </tomcat-users>

  38. Tomcat Web Application Manager • Deploy applications • Start/stop/reload

  39. Servlet Debugging • Logs • $CATALINA_HOME/logs • Interactive debugger • Use Java JPDA interface • Allows an external program to “attach” to process • Start Tomcat in debugging mode • $CATALINA_HOME/bin/catalina.sh jpda start • Start IDE debugger • Attach debugger to running Tomcat instance

  40. Session Maintenance • HTTP is stateless by default • No memory of browsers state • Preserving state between browser/web server interactions • Behavior reflects previous forms filled in and pages viewed • Kept at the browser or/and web server. • Example: Want to allow access to a given script only once a user is logged in. Don't want to require a user to login at every page.

  41. Store State At Server • Current state is stored at the server (i.e., in a file, database, or in JVM’s memory) • Each request includes a token identifying the browsers session (tokens can be passed via cookies, hidden variables, URL rewriting). • At each request, the executing servlet uses the token to fetch session state • Careful: Browser back button problem. The page the user is viewing may not reflect state stored at the server.

  42. HttpSession • One instance for each active session • Accessing/creating a session HttpSession session = request.getSession(); • Session attributes Object o = session.getAttribute("name"); session.setAttribute("name",o);

  43. Session Duration • Default: expire a session if idle (no http requests) for 30 minutes • Delete all session related attributes from server • Does not remove cookie from client • Changing session timeout • Configuration file (web.xml) <session-config> <session-timeout>30</session-timeout> </session-config> • Run-time • session.getMaxInactiveInterval() • session.setMaxInactiveInterval() • Terminating a session • session.invalidate() • Deletes session related attributes form server • Removes cookie from client

  44. Session Example

  45. Other Issues • Multithreading • HttpSession is not thread safe • Use proper synchronization to prevent concurrent property modifications • Persistent sessions • Tomcat has support for persistent sessions • Survive server restart • Saves session data to a file • Serializes properties • Property values need to be serializable • Session event listeners • Possible to create servlets that execute when a session times out • Can be use to garbage collect resources outside of the JVM

  46. ServletContext • Interface defines a servlet’s view of the web application within which the servlet is running. • Container Provider is responsible for providing an implementation of the ServletContext interface in the servlet container. • Using the ServletContext object, a servlet can • log events • obtain URL references to resources • set attributes that other servlets in the context can access.

  47. ServletContext Continued • One instance of ServletContext per web application per container ServletContext context = getServletContext(); • Provides access to Initialization Parameters • Defined in the deployment descriptor • A file called web.xml in the WEB-INF subdirectory of the app directory • Methods: getInitParameter(), getInitParameterNames()

  48. ServletContext Attributes • Context level shared objects. Can be bound into the context and accessed by any servlet that is part of the application. • Methods: setAttribute() getAttribute() getAttributeNames() removeAttributes() • More than 1 thread may be accessing a shared object. • Application developer responsible for synchronizing access to shared objects

  49. ServletContext Resources • Gives servlet access to local documents associated with the application. (i.e. static web pages, images) • Access to server logs • Methods: getResource() getResourceAsStream() getResourcePaths() log(“Error! File does not exist”);

  50. ServletContextExample

More Related