44552208-servlet

Embed Size (px)

Citation preview

  • 8/12/2019 44552208-servlet

    1/49

    SERVLET

  • 8/12/2019 44552208-servlet

    2/49

    Where are we?

    1. Intro toJava, Course

    2. Java lang. basics

    3. Arrays

    5. Encapsulation

    4. ObjectClasses 7. Inheritance

    8. Polymorphism

    10. JDBC

    6. ExceptionHandling

    Introduction Object-oriented design Advanced topics

    Newbie Programmers Developers ProfessionalsDesigners

    JAVA

    9. Abstract classesand Interfaces

    13. Servlets

    14. JSP

    Server-side coding

    12. Networking

    11.Streams

  • 8/12/2019 44552208-servlet

    3/49

    ConceptsFeatures

    javax.servlet.Servlet

    javax.servlet.http.HttpServletExample: get and send a page to clientExample: post

    Image generatingSession tracking Cookie, HttpSession, URL-rewriting

    Practical examples

    Outline

  • 8/12/2019 44552208-servlet

    4/49

    Todays buzzwords

    Applets Java programs capable of running within a

    web browser

    Servlets Java code running on server side

    Session tracking Keeping context information during a session

    of browsing related web pages

  • 8/12/2019 44552208-servlet

    5/49

    What is java servlet ?A servlet is a small Java program that runs within a Web server. Servletsreceive and respond to requests from Web clients, usually across HTTP,the HyperText Transfer Protocol. Servlet is an opposite of applet as aserver-side applet. Applet is an application running on client while servletis running on server.

    Client Server

    Request

    Response

    Servlet

  • 8/12/2019 44552208-servlet

    6/49

    What is Java Servlets?

    Servlet module run inside request/response-oriented server

    BrowserJava-enabledWeb Server Servlet Database

    HTML form

    Server

    Servlet

    = BrowserApplet

    Servlets are to Servers what Applets are to Browsers

    Substitute for CGI scriptseasier to write and fast to run

    Not part of the core Java Framework

  • 8/12/2019 44552208-servlet

    7/49

    Example use of servlet

    Processing data POST over HTTPs using HTML form as purchaseorder or credit card dataAllowing collaborative between people such as on-lineconferencing

    Many servlet can chain together among Web servers to reduceload on one Web server.

  • 8/12/2019 44552208-servlet

    8/49

    Why Use Servlets ?

    One of the reasons that Java becamepopular is Applets.

    but there are problems with Applets Browser compatibility Download bandwidth

    Server-side Java the code is executed on the server side not the

    client side a dynamically loaded module that services

    requests from a Web server

  • 8/12/2019 44552208-servlet

    9/49

    Servlets (contd.)

    vs. Common Gateway Interface (CGI) create new process for each request

    most platform independent CGI language - Perl start a new instance of interpreter for every request

    CGI runs in a completely separate process from theWeb server

    vs. Server-Side JavaScript only available on certain web servers

    vs. Active Server Pages (ASP) only available on certain web servers

  • 8/12/2019 44552208-servlet

    10/49

    CGI Communication (traditional approach)

    Web server

    Web browser

    1. request

    CGI profile file2 CGI Application(write result to CGI output file

    and terminate)

    3. execute CGI programand wait f or CGI to terminate

    CGI output file4

    5CGI terminated

    1. Web browser requset a response from CGI program.2. Web server create CGI profile file that was contain information about CGI

    variable, server and CGI output file.

    3. Web server starts CGI application and wait for its termination.4. CGI program runs and writes the result to CGI output file and then terminates.5. Web server reads from CGI output file and send back to Web browser.

  • 8/12/2019 44552208-servlet

    11/49

    Servlet Communication

    Web browser request servlet byspecified URL ashttp://www.host.com/serlet/servletNa

    meWeb server call service() method inServletLoader class which willdynamically load a specified servletname from a special directory callservlet.

    Client

    HTML

    Form

    Java-Enabled

    Web Server

    call

    Servlet

    Servlet

  • 8/12/2019 44552208-servlet

    12/49

    Servlet vs CGI

    Servlet run as light

    weight thread in

    process.

    CGI run as heavy

    weight process.

  • 8/12/2019 44552208-servlet

    13/49

    Advantage of servlet over CGI

    PlatForm IndependenceServlets can run on any platform. PERL also can be moved fromplatform to platform while CGI such as C are not portable.Performance

    Servlets only needs be loaded once, while CGI programs needs tobe load for every request so that servlet should performs fasterthan CGISecurityWhile CGI can do many insecure things, java provided security in

    language level.

  • 8/12/2019 44552208-servlet

    14/49

    Three Tier Applications.

  • 8/12/2019 44552208-servlet

    15/49

    Java Servlet Development

    Kit installation

  • 8/12/2019 44552208-servlet

    16/49

    Requirement for running java servlet

    Java Servlet APIA set of java classes. This is a Java Servlet DevelopmentKit(JSDK) that can be download from http://java.sun.com JSDK allows most standard Web server such as Netscape servers,IIS, Apache and others to load servletsJava-enabled Web serverThere are many web server that support java virtual machinesuch as Java Web server by SUN, WebSite Pro V2.0 by OReillyand the latest version of World Wide Web Consortiums free

    jigsaw Web Server.

  • 8/12/2019 44552208-servlet

    17/49

    Servlet Lifecycle

    Server loads Servlets- run init method

    Servlets Accept Request fromClients and return Data back

    - run service method

    Server removes Servlets- run destroy method

    No Concurrency Issue Server runs init only once, not per request

    service must be thread-safe - multiple service method at a timeif that is impossible, servlet must

    implement SingleThreadModel interface

    Server reloads Servlets

    - run init method

    destroy must be thread-safe - when server runs destroy, other threads

    might be accessing shared resources

  • 8/12/2019 44552208-servlet

    18/49

    A Typical Servlet Lifecycle

    from Servlet Essential 1.3.5 by Stefan Zeigerhttp://www.novocode.com/doc/servlet-essentials/

  • 8/12/2019 44552208-servlet

    19/49

    Servlet class Example

    Interface ServletDefine the standard way in which a networkserver will access a servlet. All servletclasses must (fundamentally) implementthis interface.

    GenericServletDefines a generic, protocol-independent servlet. For servlet that isnot intended to use with Web server. Towrite an HTTP servlet for use on theWeb, extend HttpServlet instead HttpServletFor Servlet that is intended to use withWeb server. This class adds HTTP-specific to work with a Web servercontext

    Servlet class

    GenericServletclass

    HttpServletclass

    http://localhost/var/www/apps/conversion/java/servlet_doc/javax/servlet/http/HttpServlet.htmlhttp://localhost/var/www/apps/conversion/java/servlet_doc/javax/servlet/http/HttpServlet.html
  • 8/12/2019 44552208-servlet

    20/49

    Servlet Structure

    All servlet classes and interfaces that form the APIare found in the javax.servlet package. All servlets, no matter what type of server theyare destined to be used with, implement the

    javax.servlet.Servlet interface. This interface definesthe basic functionality that a servlet must possess

  • 8/12/2019 44552208-servlet

    21/49

    ServletConfig

    When the servlet first starts up, the systemcan pass specific initialization informationto the servlet for possible processing via

    the init ...) method.Parameters are passed in using akey/value pairing, and two methods areprovided to access this data: getInitParameter ...) and getInitParameterName ).

  • 8/12/2019 44552208-servlet

    22/49

    ServletContext

    allows the servlet to interrogate the serverabout various pieces of environmental dataExample :

    Many servers, particularly web servers, refer tofiles and resources as virtual files. However, thismakes opening up files difficult, as the virtualfile or alias needs to be mapped onto a real file.The ServletContext interface, for example, providesa method to convert an alias and real path filenames.

  • 8/12/2019 44552208-servlet

    23/49

    ServletContext

  • 8/12/2019 44552208-servlet

    24/49

    GenericServletThe base class on which the majority ofservlets are based is the GenericServlet class.

  • 8/12/2019 44552208-servlet

    25/49

    Interface Servlet class

    void init( ServletConfig ) Initialized the servlet when it is loaded into server (system).

    abstract void service( ServletRequest, ServletResponse ) This is an abstract class so that it must be implemented by a subclass ofGenericServlet class. A method that the servlet processeseach client request

    destroy() This method is called when the server remove a servlet from memory.

  • 8/12/2019 44552208-servlet

    26/49

    ServletRequest

  • 8/12/2019 44552208-servlet

    27/49

  • 8/12/2019 44552208-servlet

    28/49

    ServletResponse

    The most important method of thisinterface is the getOutputStream ) method.This returns the ServletOutputStream, whichcan be used to provide any otherpreferred output stream class from the java.io package.

  • 8/12/2019 44552208-servlet

    29/49

    GenericServlet : Example

  • 8/12/2019 44552208-servlet

    30/49

    GenericServlet

  • 8/12/2019 44552208-servlet

    31/49

    Web-Based Servlet

    The developers at Java recognized thefact that the majority of servlets would beemployed in the field of the Internet, withparticular emphasis on the world wideweb. The servlet API offers you a directalternative to using CGI and Microsoft'sActive Server Pages (ASP) to implementserver-side solutions. To make codingservlets for the web relatively easy, aspecial HttpServlet class was developed.This provided methods to access themore common header fields found in theHTTP protocol.

  • 8/12/2019 44552208-servlet

    32/49

  • 8/12/2019 44552208-servlet

    33/49

    HttpServlet

    The HttpServlet, based on the GenericServlet class.It provides an improved interface fordealing with HTTP-specific clientrequests.In addition to the service ...) method that isused to deal with all requests, sevenadditional methods exist for processing

    requests; doGet ...), doPost ...), doHead ...),doPut ...), doTrace ...), doOptions ...) , anddoDelete ...).

  • 8/12/2019 44552208-servlet

    34/49

    Servlet Architecture Overview - HTTP servlets

    IS-A

    Servletinterface

    Servlet

    Client

    GET

    POSTServlet

    doGet(ServletRequest req, ServletResponse res);ServletRequest

    ServletResponse

    ServletResponnse

    ServletRequestdoPost(ServletRequest req, ServletResponse res);

    parameters, protocol, remote host,ServerInputStream(binary data etc..)

    mime type to reply,reply data,

    ServletOutputStream

  • 8/12/2019 44552208-servlet

    35/49

    HttpServlet Interface

  • 8/12/2019 44552208-servlet

    36/49

    ServletRequest Interface

    This interface return information about parameter sent withthe request.

    int getContentLength()

    String getContentType() String getProtocol()String getScheme() String getServerName()

    int getServerPort() String getRemoteAddr()

  • 8/12/2019 44552208-servlet

    37/49

    HttpServletRequest :

  • 8/12/2019 44552208-servlet

    38/49

    ServletRequest Interface (continued)

    String getRemoteHost() String getRealPath( String path) ServletInputStream getInputStream() String getParameter( String name) String[] getParameterValues( String name) Enumeration getParameterNames() Object getAttribute( String name)

  • 8/12/2019 44552208-servlet

    39/49

    ServletResponse Interface

    This interface defined method for sending information back toWeb browser.void setContentLength( int len)void setContentType( String type)

    ServletOutputStream getOutputStream()

  • 8/12/2019 44552208-servlet

    40/49

    HttpServletRequest Interface

    The method of HttpServletRequest interface inherits the methodin ServletRequest interface. GET, POST, and HEAD in HTTP arealso supported.

  • 8/12/2019 44552208-servlet

    41/49

    Servlets (contd.)

    HttpServletRequest information sent from the client

    getParameter() getParameterValues() getParameterNames()

    will discuss in detail later in FormPost HttpServletResponse

    information sent to the client getWriter()

    return an instance of PrintWriter you can use print and println with a PrintWriter see SimpleServlet

  • 8/12/2019 44552208-servlet

    42/49

  • 8/12/2019 44552208-servlet

    43/49

    HttpServletResponse Interface

    String getMethod()String getServletPath()String getPathInfo()String getPathTranslated()String getQueryString()

    String getRemoteUser()String getAuthTypeString getHeader(String name)String getIntHeader(String name)

    long getDateHeader()Enumeration getHeaderNames()

  • 8/12/2019 44552208-servlet

    44/49

    Writing the Servlet

    Implement the javax.servlet.Servletinterface

    HTTP: extends javax.servlet.http.HttpServlet

    class

    public class SurveyServlet extends HttpServlet {

    /* typical servlet code, with no threading concerns* in the service method. */

    ...}

  • 8/12/2019 44552208-servlet

    45/49

    Interacting with Clients(1)- HTTP servlets

    doGet

    doPost

    doPut

    doDelete

    ClientGet

    Post

    PutDelete

    HttpServletRequest - argument & HTTP header data String[] getParameterValues(String name) - get user parameter

    For GET method- String getQueryString() For POST, PUT, DELETE method

    - BufferedReader getReader() - text data - ServletInputStream getInputStream() - binary data

    methods

  • 8/12/2019 44552208-servlet

    46/49

  • 8/12/2019 44552208-servlet

    47/49

    Example of an HTTP Servlet -GET/HEAD methods

    public class SimpleServlet extends HttpServlet {public void doGet (HttpServletRequest req, HttpServletResponse res)

    throws ServletException, IOException {// set header field first

    res.setContentType("text/html"); // then get the writer and write the response dataPrintWriter out = res.getWriter(); out.println ( SimpleServlet );out.println ( SimpleServlet Output );out.println ( );out.close();

    }public String getServletInfo() {

    return " A simple servlet ";} }

  • 8/12/2019 44552208-servlet

    48/49

    Example (2) use ofHttpServlet

  • 8/12/2019 44552208-servlet

    49/49

    Accessing web-based servlets

    Assume the servlets' class file hasbeen placed in the server's servletsdirectory. The servlet can be called

    by including /servlet/ before theservlet name in the URL.For example, if you set the classname of the sample servlet to TestServlet, then it could be accessedusing http:///servlet/TestServlet