290 likes | 374 Views
Chapter 1: Overview of Servlets and JavaSerevr Pages. What Are Servlets: Replacement for CGI Basic operations: receive, process, send Advantages over CGI and other techniques: Efficient Convenient Powerful Portable Secure Inexpensive.
E N D
What Are Servlets: Replacement for CGI • Basic operations: receive, process, send • Advantages over CGI and other techniques: • Efficient • Convenient • Powerful • Portable • Secure • Inexpensive
What is JavaServer Pages (JSP): Enables you to mix static HTML with dynamically generated content. • Advantages of JSP Versus: • ASP: Dynamic part is written in JAVA • PHP: Extensive library for Networking, DB, distributed Objects • Pure Servlets: Easier to develop specially if the pages are almost static ones. • SSI: More powerful set of tools • JavaScript: Access DB and networking • Static HTML: You know • Installing s/w: Available In Windows machine Stright107.
Basic Servlet structure: ServletTemplate.java • Simple Servlet generating plain text: HelloWorld.java • A Servlet that generates HTML: HelloWWW.java (Always set Content type first) • Packaging Servlets: HelloWWW2.java • Simple HTML-Building Utilities: ServletUtilities.java &HelloWWW3.java
The Servlet life cycle: • The init() method: With/Without parameters • The service() method: support HEAD, OPTIONS, and TRACE requests. Call doGet, doPost, doXxx • Implementing the SingleThreadModel • The destroy() method: performs cleaning up • Using Initialization Parameters: ShowMessage.java • Using Modification Date: LotteryNumbers.java • Debugging Servlets: log, command windows, stop/start, look and request/response data • Sending HTTP request: WebClient.java
Reading Form Data: methods getParameter(“name”), getParameterValues(“name”), getParameterNames() • Example: ThreeParams.java and .html • Using GET and POST: ShowParametersGetForm.htm, ShowParametersPostForm.htm, & ShowParameters.java • A resume posting service: SubmitResume.htm & SubmitResume.java • Filtering HTML specific characters: BadCodeServlet.java, FilteredCodeServlet.java
The request object has a number of methods to enable you to access all the headers of an HTTP request • getHeader(), getContentLength(), getContentType(), getHeadersName(), etc. • Other methods such as getMethod(), getProtocol(), etc. can access info into the request line • Example: ShowRequestHeaders.java
HTTP 1.1 request headers are case insensitive and include: • Accept (MIME type) • Accept-Encoding, Accept-Language, Accept-Charset • Authorization • Connection • Content-Length • Content-type • From (Email address of the sender- Only sent by web Spiders) • Host, User-Agent, Via, ……etc
Sending compressed web pages: EncodedPage.java • Restricting access to Web page: ProtectedPage.java and PasswordBuilder.java
The standard CGI variables can be accessed using servlets but in many cases we really do not want to do so. • Examples: CONTENT_LENGTH, DOCUMENT_ROOT, QUERY_STRING, ETC. • Program example: ShowCGIVariables.java
Chapter 6: Generating the Server Response: HTTP Status Codes
The status code is usually returned using response.setStatus(int code) • There are two other methods sendError(int code, String message) & sendRedirect(String URL) • Generally, there is five categories • 100-199: Informational • 200-299: Request success • 300-399: Files moved (usually indicates a location header) • 400-499: Client error • 500-599: Server error
Example: Front end to various search engines • Files: SearchEngines.java, SearchSpec.java, SearchEngines.html
Chapter 7: Generating the Server Response: HTTP Response Headers
Any permitted header can be set by using the method setHeader(String header name, String value); • In Servlets 2.2 setHeader() replace existing ones so you can use addHeader() to add new entries of an already existed header • Convenient methods setContentType(), setContentLength(), addCookie(), sendRedirect() • Some common headers: Connection, Content-Language, Content-Type, Content-Length, Location, Refresh { response.setHeader(“Refresh”, “5”); }
Persistent Servlet and auto-reloading • Handling multiple simultaneous connections: • Maintaining state between requests or even among various servlets in the same engine using the ServletContext object (getServletContext()) • Code: PrimeNumbers.java, PrimeList.java, Primes.java • Persistent HTTP connections: PersistentConnection.java & ImageRetriever.java • Generating Gif Images: ShadwedText.java & MessageImage.java
Steps: • Create a cookie: new Cookie(name. value) • Access attributes: cookie.setXxx(), cookie.getXxx() • Insert it into response header: addCookie(cookie) • Get all cookies: request.getCookies(), returns array of cookies objects • Use getName() and getValue() methods of cookie • Examples: setCookies.java & ShowCookies.java • Customized search engine: CustomizedSearchEngine.java & SearchEngineFrontEnd.java
A very attractive alternative to Servlets specially if the page is mostly static with few dynamic parts • Advantages: Widely supported & using JAVA!!! • The JSP page is automatically converted to normal Servlet! • Three types of JSP constructs • Scripting elements: Java code that will become part of the resultant Servlet • Directives: Control the overall Servlet structure • Actions: Specifying components that control JSP engine
Scripting Elements: • Expressions: <%= expression %> • Scriptlets: <% code %> {inserted into _jspService method called by the service method} • Declaration: <%! Code %> {code inserted outside any existing method • Expressions example: Expressions.jsp • Scriptlets: in many situations you need more complex behavior than what simple expressions can do • Example: BGColor.jsp
JSP Directives: Contain code that will be inserted in the main body of the resultant Servlet. Ex <%! String str=“str” %> • They are normally used in conjunction with Expressions • Example: AccessCounts.jsp • Predefines Variables: Simplify JSP code • request: The request object!! • response: The response object!! • out: An object of type JSPWriter which is a child of PrintWriter • application: The ServletContext object
There are three types of directives: • page: import classes, select parent, set content type • include: Insert a file in the Servlet class during JSP file translation • taglib: allow you to define custom markup tags • The page directives has a number of case-sensitive attributes. • General form: <%@ page attr=“value”%> • The “import” attribute, ex ImportAttribute.jsp • The “contentType” attribue: ex ContentType.jsp to return text/plain. Ex, Excel.jsp to return Excel spread sheet using tabs & ApplesAndOranges.jsp using tables.
The “isThreadSafe” attribute: default is true otherwise specify false for the SingleThreadModel • The “buffer” & “autoflush” attributes • The “errorPage” and “isErrorPage” attributes: ex ComputeSpeed.jsp & SpeedError.jsp