1.24k likes | 1.25k Views
Dive into Servlets, HTML, and Web Apps with this complete guide covering structure, HTTP, forms, elements, capabilities, HTTP communication, request, methods, headers, and server responses.
E N D
Servletsand Web Applications (WARs) HTML, Servlets, and Web Applications Servlets & Web Apps
Topics • HTML Review • Servlets • Web Applications • Resources • References Servlets & Web Apps
HTML • Basic Document Structure • Hyper-Text Transport Protocol (HTTP) • Forms Servlets & Web Apps
HTML • Regular text with ‘markup’ elements specifying the desired appearance and layout of the information • Style sheets can also be specified • Tag Format • <TAG ATTR=optional>Value</TAG> Servlets & Web Apps
HTML Example <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 3.2//EN”> <HTML> <HEAD> <TITLE>Example Page</TITLE> </HEAD> <BODY BGCOLOR = "WHITE"> <BLOCKQUOTE> <H3>Bonus Calculation</H3> </BLOCKQUOTE> </BODY> </HTML> Servlets & Web Apps
HTML Structure <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 3.2//EN”> <HTML> <HEAD> <TITLE>This is the title</TITLE> </HEAD> <BODY> <H1>Heading</H1> Other elements </BODY> </HTML> Servlets & Web Apps
Example Tags • <HTML><HEAD><BODY> • Main document sections • Headings <H1><H2> …. <H6> • Paragraph <P> (</P> is optional) • Lists • Numbered List <OL><LI> ….. </OL> • Bulleted Lists <UL><LI> ….. </UL> Servlets & Web Apps
Other Capabilities • Character Display • Bold <B>, Italic <I>, Font <F>, etc. • Hyperlinks <A HREF=url>Click</A> • Tables • Forms • Frames • Scripting Servlets & Web Apps
HTTP • Simple, socket-based protocol used between web browsers and web servers • Defaults to port 80 • Client Request • Server Response Servlets & Web Apps
HTTP Client Request • Request message consists of four parts • Request Line • Request Header(s) • Blank Line • Additional Data (Optional) • Example: • GET / HTTP/1.0 • Accept: */* • Blank Line Servlets & Web Apps
Request Line • Request Line • Example • GET /test.html HTTP/1.1 • Request Type (GET, POST, HEAD, PUT, DELETE) • Document Address • Uniform Resource Identifier (URI) • URL with no protocol, host, or port • http://java.sun.com/test.html ===> /test.html • HTTP Version Servlets & Web Apps
Request Methods • GET (HTTP 1.0) • Used by browsers for normal document requests • Additional info can be sent after URI GET /test.html?field1=value HTML/1.0 • Use for repeatable (bookmarkable) actions • POST (HTTP 1.0) • Additional info sent after blank line (not after URI) • Can transmit more information than GET • Use for non-repeatable (non-bookmarkable) actions • HEAD (HTTP 1.0) • Server only returns response headers • Used to verify links or obtain server information without receiving documents Servlets & Web Apps
Request Methods (cont.) • PUT (HTTP 1.1) • Client can supply document for storage on the server • DELETE (HTTP 1.1) • Client can delete a URI from the server • OPTIONS (HTTP 1.1) • Query for supported options on the server • TRACE (HTTP 1.1) • Have server echo back passed document unchanged Servlets & Web Apps
Request Headers • Additional, optional information for server • Examples • Accept - MIME types client will accept in preference order • Accept */* - client is willing to accept anything • Authorization:auth-scheme:credentials • provides no privacy alone - can be combined with SSL • Connection: Keep-Alive • do not close connection between server interactions • Content-Length - data length (POST) • Cookie:name=val;name2=val2 • Referrer - URL of referring page • Host - host and port from original URL Servlets & Web Apps
Request Example $ telnet www.apl.jhu.edu 80 Trying 128.220.101.100... Connected to aplcenmp.apl.jhu.edu. Escape character is '^]'. GET /~jcstaff/ HTTP/1.1 Host: www.apl.jhu.edu:80 Servlets & Web Apps
HTTP Server Response HTTP/1.1 200 OK Date: Sun, 29 Sep 2002 05:12:19 GMT Server: Apache/1.3.26 (Unix) Last-Modified: Wed, 25 Sep 2002 04:14:25 GMT ETag: "80629-8d0-3d913821" Accept-Ranges: bytes Content-Length: 2256 Content-Type: text/html <!doctype html public "-//w3c//dtd html 4.0 transitional//en"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> ... </html> Connection closed by foreign host. Servlets & Web Apps
Server Response (Cont) • Consists of: • Status Line • HTTP/Version status-code message • Success 200-299, File Moved 300-399, Client error 400-499, Server Error 500-599 • Response Header(s) • Blank Line • Referenced Document Servlets & Web Apps
HTTP Response Headers • Examples • Content-Length - File length • Content-Type - MIME Type • text/html, audio/x-proprietary • Last-Modified - date/time of document modification • Set-Cookie • WWW-Authenticate Servlets & Web Apps
Response Header Example HTTP/1.0 200 OK Date: Fri, 29 Feb 2000 17:31:20 GMT Set-Cookie: user-id=123; secure Content-Length: 124 Content-Encoding: x-compress Content-Type: text/html <Blank Line> HTML document Servlets & Web Apps
Dynamic Page Generation • Web Servers were built to distribute web pages. • HTML page can be ‘marked-up’ for processing by the server • Active Server Pages (ASP), • Java Server Pages (JSP) • Web Server can be configured to route specific URI requests to user code • Common Gateway Interface (CGI) • Servlets Servlets & Web Apps
HTML Forms • Gathers user information and submits to CGI/Servlet programs • GET • Form parameters appended to end of URI • Simple, but limited in length and security • POST • FORM parameters sent in message body Servlets & Web Apps
Form Example <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"> <HTML> <HEAD> <TITLE>Form Submission Demonstration</TITLE> </HEAD> <BODY> <FORM ACTION="showForm" METHOD=”GET" ENCTYPE="application/x-www-form-urlencoded"> <P>Please enter your email address for our records</P> <P>Email Address: <INPUT TYPE="TEXT" NAME="address" SIZE="25"></P> <P><INPUT TYPE="SUBMIT" NAME="Submit" VALUE="Submit"> </FORM> </BODY> </HTML> Servlets & Web Apps
Form Display Servlets & Web Apps
Form Structure • Form Header • <FORM Method=GET ACTION=url> • Attributes • Action - URL of processing script • Method - HTTP method (GET or POST) • Input Field(s) • <INPUT TYPE=type NAME=name></INPUT> • Action Button(s) • <INPUT TYPE=type NAME=name VALUE=value></INPUT> Servlets & Web Apps
Input Fields • GUI controls for entering information • Types • Text Box <INPUT TYPE=“TEXT”> • Password Box <INPUT TYPE=“PASSWORD”> • Checkbox <INPUT TYPE=“CHECKBOX”> • Radio Button <INPUT TYPE=“RADIO”> • Hidden Field <INPUT TYPE=“HIDDEN”> • Images <INPUT TYPE=“IMAGE”> • File <INPUT TYPE=“FILE”> • Text Window <TEXTAREA>…</TEXTAREA> • Menu <SELECT>…<OPTION>…</SELECT> Servlets & Web Apps
Form Example <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"> <HTML> <HEAD> <TITLE>untitled</TITLE> </HEAD> <BODY> <FORM ACTION="snoop" METHOD="POST" ENCTYPE="application/x-www-form-urlencoded"> <P>Please enter various fields so we can see what is sent</P> <P><BR> Checkbox: <INPUT TYPE="CHECKBOX" NAME="CheckBox" VALUE="CheckBox"></P> <P>Text Field: <INPUT TYPE="TEXT" NAME="TextField" SIZE="25"></P> <P>List Box: Servlets & Web Apps
<SELECT NAME="Selection" SIZE="3" MULTIPLE> <OPTION SELECTED>Option 1</OPTION> <OPTION>Option 2</OPTION> <OPTION>Option 3</OPTION> </SELECT> </P> <P><INPUT TYPE="SUBMIT" NAME="Submit" VALUE="Submit"> </FORM> </BODY> </HTML> Servlets & Web Apps
Menu Display Servlets & Web Apps
Form Submission • Parameters are encoded and sent to the Action URL using GET or POST • application/x-www-form-urlencoded name1=val1&name2=val2&namex=valx space ===> ‘+’ non-alphanumeric ===> %xx • ‘~’ becomes %7E • ‘/’ becomes %2F Servlets & Web Apps
Form Submission (Cont) • Web Server makes parameters available via the environment for CGI programs • Perl and Java are common implementation languages • Utility Libraries for decoding parameters • Parameters are made available to servlets via the HttpRequest object Servlets & Web Apps
Forms Summary • Forms provide a simple mechanism to gather user input and submit to server-side programs • For more complex user interfaces, consider a Java applet/program • presents user interface and gathers input • opens socket to web server • sends HTTP formatted GET/POST message Servlets & Web Apps
Servlets Servlets & Web Apps
Servlet Definition • “Web component, managed by a container, that generates dynamic content” • Request-Response mechanism modeled after HTTP • Required by J2EE specification • Web Server configured to invoke servlets when specified URLs are accessed (servlet mapping) • HTML Forms • Java programs Servlets & Web Apps
Servlet Benefits • Efficiency • run as threads vs. CGI processes • Written in Java • can use any Java API such as JDBC, EJB, RMI, etc. • Portability • supported by many web/application servers • Simplicity • Provides support for common operations including session management Servlets & Web Apps
Servlet Container • Provides the execution environment for a servlet • Must support HTTP as the request/response protocol • HTTP 1.1 support strongly recommended by spec • May support HTTPS (HTTP over SSL) • Can be installed directly in a web server or as an add-on using web server extension mechanisms • May impose security constraints on servlet Servlets & Web Apps
Servlet Container (Cont) • Web Application (servlet/jsp/html deployment) can be marked as distributable in the servlet 2.2 specification • Servlet can be deployed in multiple JVMs running on one or more hosts • Deployed servlets must obey restrictions Servlets & Web Apps
Architecture Get/Post Request Request Web Browser Web Server Servlet Container HTML Page Reply Servlet Servlets & Web Apps
Key Servlet Classes Servlets & Web Apps
Servlet Lifecycle • init() called when servlet is instantiated • service() called to handle requests throughout the servlet’s lifetime • destroy() called when servlet engine unloads the servlet instance • period of inactivity • resource issues Servlets & Web Apps
Servlet Implementation package corej2ee.examples.web; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class FormServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req,res); } Servlets & Web Apps
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<html>"); out.println("<head><title>Form Servlet</title></head>"); out.println("<body>"); out.println("<h1>Registered email:</h1>"); out.println(req.getParameter("address")); out.close(); } } Servlets & Web Apps
Request and Reply • Request URL http://localhost:7001/form/showForm?address=dan@weimer.com Servlets & Web Apps
Reply Document <html> <head><title>Form Servlet</title></head> <body> <h1>Registered email:</h1> dan@weimer.com </body> </html> Servlets & Web Apps
Understanding the Request • Form parameters • String choice=request.getParameter(“Product”); • Cookies • Cookie[] = request.getCookies() • getName(), getValue() • Binary Data • InputStream is = request.getInputStream() • Character Data • Reader r = request.getReader() Servlets & Web Apps
Requests and Responses Servlets & Web Apps
Generating a Response • ServletResponse permits servlet to generate output: • setContentType( mimeType ) • setContentLength( int len) • getOutputStream() : ServletOutputStream • binary output to web browser • getWriter() : Writer • character output for web browser Servlets & Web Apps
HttpServletResponse • Extends ServletResponse to allow HTTP-specific information to be communicated • setHeader(String header, String value) • addCookie(Cookie cookie) • sendError(int sc, String msg) • setStatus(int sc) Servlets & Web Apps
HTTP Headers Examples • HttpServletResponse methods • setHeader,setDataHeader,setIntHeader • HTTP response headers • Allow • Content-Encoding • Expires • Last-Modified Servlets & Web Apps
Example Response Headers(Disable Client Caching) response.setDateHeader(“Expires”, 0); response.setHeader(“Pragma”, “no-cache”); if(request.getProtocol().equals(“HTTP/1.1”)) { response.setHeader(“Cache-Control”, “no-cache”); } Servlets & Web Apps