Presentation is loading. Please wait.

Presentation is loading. Please wait.

L.MARIA MICHAEL VISUWASAM UNIT-4

Similar presentations


Presentation on theme: "L.MARIA MICHAEL VISUWASAM UNIT-4"— Presentation transcript:

1 L.MARIA MICHAEL VISUWASAM UNIT-4
SERVLET 4/25/2017 L.MARIA MICHAEL VISUWASAM UNIT-4

2 Where are we? JAVA Object-oriented design Introduction Advanced topics
4/25/2017 Where are we? JAVA Object-oriented design Introduction Advanced topics Server-side coding 10. JDBC 4. Object Classes 1. Intro to Java, Course 7. Inheritance 11.Streams 2. Java lang. basics 6. Exception Handling 13. Servlets 5. Encapsulation 14. JSP 3. Arrays 8. Polymorphism 12. Networking 9. Abstract classes and Interfaces Newbie Programmers Designers Developers Professionals L.MARIA MICHAEL VISUWASAM UNIT -4

3 Outline Concepts Features javax.servlet.Servlet
Example: get and send a page to client Example: post Session tracking Cookie, HttpSession Practical examples

4 Today’s buzzwords Applets Servlets Session tracking
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

5 What is java servlet ? 1. A servlet is a small java program that runs within a web server. 2. Servlets receive and respond to requests from web clients, usually across HTTP. 3. Servlet is an opposite of applet as a server-side applet. Applet is an application running on client while servlet is running on server.

6 = What is Java Servlets? Servlet Browser Java-enabled Web Server
4/25/2017 What is Java Servlets? Servlet module run inside request/response-oriented server Browser Java-enabled Web Server Servlet Database HTML form Servlets are to Servers what Applets are to Browsers Servlet = Applet 1. 서블릿의 개념 - 서버측에서 클라이언트측의 요구를 받아 그에 대한 처리를 한 후 결과를 되돌리는 모듈이다. 2. 애플릿/서블릿 애플릿은 서버측에서 작성되었지만, 코드가 클라이언트로 다운로드되어 실행되는 반면, 서블릿은 서버 측에서 직접 실행되어 그 결과만 반환된다는 점에서 오히려 CGI와 비슷하다. 하지만,CGI보다는 요구와 결과를 처리하는 방법이 더 쉽다. 3. JDK의 기본 패키지가 아니다. 서블릿을 작성하려면, JDK외에 JSDK(98년 중반 현재 2.0까지 발표)를 다운로드받아야 한다. 4. 서블릿을 동작시키려면, 서블릿 실행을 처리할 수 있는 웹 서버 또한 존재해야 한다. Server Browser L.MARIA MICHAEL VISUWASAM UNIT -4

7 Example use of servlet Processing data POST over HTTPs using HTML form as purchase order or credit card data Allowing collaborative between people such as on-line conferencing Many servlet can chain together among Web servers to reduce load on one Web server.

8 Why Use Servlets ? One of the reasons that Java became popular 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

9 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 the Web server vs. Server-Side JavaScript only available on certain web servers vs. Active Server Pages (ASP)

10 Servlet Communication
Web browser request servlet by specified URL as Web server call service() method in ServletLoader class which will dynamically load a specified servlet name from a special directory call servlet.

11 Servlet vs CGI Servlet run as light weight thread in process.
CGI run as heavy weight process.

12 Advantage of servlet over CGI
PlatForm Independence Servlets can run on any platform. PERL also can be moved from platform to platform while CGI such as C are not portable. Performance Servlets only needs be loaded once, while CGI programs needs to be load for every request so that servlet should performs faster than CGI Security While CGI can do many insecure things, java provided security in language level.

13 Servlet Lifecycle Server loads Servlets - run init method
4/25/2017 Servlet Lifecycle No Concurrency Issue Server runs init only once, not per request Server loads Servlets - run init method Servlets Accept Request from Clients and return Data back - run service method service must be thread-safe - multiple service method at a time if that is impossible, servlet must implement SingleThreadModel interface Server removes Servlets - run destroy method destroy must be thread-safe - when server runs destroy, other threads might be accessing shared resources Server reloads Servlets - run init method L.MARIA MICHAEL VISUWASAM UNIT -4

14 Methods of the Servlet Interface
Description destroy( ) Called by the servlet container to indicate to a servlet that the servlet is being taken out of service. getServletConfig( ) Returns a ServletConfig object, which contains initialization and startup parameters for this servlet. getServletInfo( ) Returns information about the servlet, such as author, version, and copyright. init( ) Called by the servlet container to indicate to a servlet that the servlet is being placed into service. service( ) Called by the servlet container to allow the servlet to respond to a request.

15 Servlet Overview and Architecture (cont.)
Servlets are more commonly used when a small portion of the content sent to the client is static text or markup. In fact, some servlets do not produce content. Rather, they perform a task on behalf of the client, then invoke other servlets or JSPs to provide a response. Note that in most cases servlet and JSP technologies are interchangeable. The server that executes a servlet is referred to as the servlet container or servlet engine. Servlets and JSP have become so popular that they are now supported directly or with third-party plug-ins by most major Web servers and application servers (servers that execute applications to generate dynamic Web pages in response to requests).

16 Servlet Overview and Architecture (cont.)
Servlet Container HTTP request HTTP request Web Browser Web Server Servlet    Servlet HTTP response HTTP response Database We’ll look at servlets that implement the request-response model between clients and servers using the HTTP protocol. This architecture is shown in the diagram above.

17 Servlet Overview and Architecture (cont.)
Explanation of the architecture diagram on previous page A client application sends an HTTP request to the server. The servlet container receives the request and directs it to be processed by the appropriate servlet. The servlet does its processing, which may include interacting with a database or other server-side components, such as other servlets or JSPs. The servlet returns its results to the client – normally in the form of an HTML, XHTML, or XML document to display in a browser.

18 Servlet classes Example
Interface Servlet Define the standard way in which a network server will access a servlet. All servlet classes must (fundamentally) implement this interface. GenericServlet Defines a generic, protocol-independent servlet. For servlet that is not intended to use with Web server. To write an HTTP servlet for use on the Web, extend HttpServlet instead. HttpServlet For Servlet that is intended to use with Web server. This class adds HTTP-specific to work with a Web server context

19 Servlet Structure All servlet classes and interfaces that form the API are found in the javax.servlet package. All servlets, no matter what type of server they are destined to be used with, implement the javax.servlet.Servlet interface. This interface defines the basic functionality that a servlet must possess

20 Servlet Interface The servlet packages define two abstract classes that implement interface Servlet – class GenericServlet (from the package javax.servlet) and class HttpServlet (from the package javax.servlet.http). These classes provide default implementations of some Servlet methods. Most servlets extend either GenericServlet or HttpServlet and override some or all of their methods. The GenericServlet is a protocol-indpendent servlet, while the HttpServlet uses the HTTP protocol to exchange information between the client and server. We’re going to focus exclusively on the HttpServlet used on the Web.

21 Servlet Interface (cont.)
HttpServlet defines enhanced processing capabilities for services that extend a Web server’s functionality. The key method in every servlet is service, which accepts both a ServletRequest object and a ServletResponse object. These object provide access to input and output streams that allow the servlet to read data from and send data to the client. If a problem occurs during the execution of a servlet, either ServletExceptions or IOExceptions are thrown to indicate the problem.

22 HttpServlet Class Servlets typically extend class HttpServlet, which overrides method service to distinguish between the various requests received from a client web browser. The two most common HTTP request types (also known as request methods) are get and post. A get request retrieves information from a server. Typically, an HTML document or image. A post request sends data to a server. Typically, post requests are used to pass user input to a data-handling process, store or update data on a server, or post a message to a news group or discussion forum. Class HttpServlet defines methods doGet and doPost to respond to get and post requests from a client.

23 HTTPServlet Class (cont.)
Methods doGet and doPost are invoked by method service, which is invoked by the servlet container when a request arrives at the server. Method service first determines the request type, the invokes the appropriate method for handling such a request. In addition to methods doGet and doPost, the following methods are defined in class HttpServlet: doDelete (typically deletes a file from the server) doHead (client wants only response headers no entire body) doOptions (returns HTTP options supported by server) doPut (typically stores a file on the server) doTrace (for debugging purposes)

24 HTTPServletRequest Interface
Every invocation of doGet or doPost for an HttpServlet receives an object that implements interface HttpServletRequest. The servlet container creates an HttpServletRequest object and passes it to the servlet’s service method, which in turn, passes it to doGet or doPost. This object contains the clients’ request and provides methods that enable the servlet to process the request.

25 HTTPServletRequest Methods
Cookie[] getCookies() – returns an array of Cookie objects stored on the client by the server. Cookies are used to uniquely identify clients to the server. String getLocalName() – gets the host name on which the request was received. String getLocalAddr() – gets the IP address on which the request was received. int getLocalPort() – gets the IP port number on which the request was received. String getParameter( String name) – gets the value of a parameter set to the servlet as part of a get or post request.

26 HTTPServletResponse Methods
void addCookie (Cookie cookie) – adds a Cookie to the header of the response to the client. ServletOutputStream getOutputStream() – gets a byte-based output stream for sending binary data to the client. PrintWriter getWriter() – gets a character-based output stream for sending text data (typically HTML formatted text) to the client. void SetContentType (String type) – specifies the content type of the response to the browser to assist in displaying the data. void getContentType() – gets the content type of the response.

27 Example of an HTTP Servlet - GET/HEAD methods
4/25/2017 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 data PrintWriter out = res.getWriter(); out.println("<HEAD><TITLE> SimpleServlet</TITLE></HEAD> <BODY>"); out.println("<h1> SimpleServlet Output </h1>"); out.println("</BODY>"); out.close(); } public String getServletInfo() { return "A simple servlet"; } } L.MARIA MICHAEL VISUWASAM UNIT -4

28 Accessing web-based servlets
Assume the servlets' class file has been placed in the server's servlets directory. The servlet can be called by including /servlet/ before the servlet name in the URL. For example, if you set the class name of the sample servlet to TestServlet, then it could be accessed using

29 Creating a Web Application (cont.)
The most basic web application in Tomcat will require the creation of a directory inside the webapps directory to hold the web application. For this first example, we’ll create a subdirectory called first-examples. Create this directory inside the webapps directory of Tomcat.

30 Creating a Web Application (cont.)
Within the first-examples directory we need to create a directory that will hold the configuration and all of the resources for the web application. This directory must be called WEB-INF. The most important and only required element in WEB-INF is the file web.xml. The web.xml file controls everything specific to the current web application. We’ll look at this file in more detail later as we add to it, but for now we’ll look only at the components of this file that are essential for a very simple web application. The next page illustrates our initial web.xml file.

31 Creating a Web Application (cont.)
The web-app tag Optional display-name tag. Used by administrator tools. Optional description for reading the xml file. Servlet declaration. Specifies the name of the servlet, the implementing class file, and any initialization parameters. Servlet mapping associates a servlet name with a class of URLs. One servlet may be configured to handle multiple sets of URLs, however, only one servlet can handle any given URL.

32 Creating a Web Application (cont.)
With these directories and files in place, Tomcat will be able to respond to a request for the page from a client athttp://localhost:8080/first-examples/WelcomeServlet.html. Other HTML and JSP pages can be added at will, along with images, MP3 files, and just about anything else. Although what we have just seen is all that is required to create a minimal web application, much more is possible with a knowledge of how web applications are arranged and we will see this as we progress through this technology. The next few slides illustrate the execution of our simple web application (a welcome servlet).

33 Execution of the WelcomeServlet
Client invokes the WelcomeServlet page from the web application named first-examples. This is the XHTML file that generates the output shown above which informs the client how to invoke the servlet. Page 30

34 Execution of the WelcomeServlet servlet
Page 31

35 An XHTML Document The XHTML document shown on page 30 provides a form that invokes the servlet defined on page 23. The form’s action attribute (/first-examples/welcome1) specifies the URL path that invokes the servlet. The form’s method attribute indicates that the browser sends a get request to the server, which results in a call to the servlet’s doGet method. We’ll look at how to set-up the URL’s and deployment structure in the next set of notes.

36 Set-Up For First Web Application
The exact set-up you need to use for setting up your web application in Tomcat is summarized on the next couple of pages. In the Tomcat webapps folder create a directory named first-examples. In the top level of first-examples copy the WelcomeServlet.html file from the course code page. In the top level of first-examples create a directory named WEB-INF. When steps 2 and 3 are complete the top level of first-examples should look like the picture at the top of the next page.

37 Set-Up For First Web Application (cont.)
Top level of first-examples. Copy the web.xml configuration file from the course code page into the WEB-INF directory. At the top level of the WEB-INF directory create a directory named classes. When steps 5 and 6 are complete, the WEB-INF directory should look like the picture on the top of the next page.

38 Set-Up For First Web Application (cont.)
Copy the WelcomeServlet.java file from the course code page into the classes directory and compile it to produce the WelcomeServlet.class file which should also reside in the classes directory. (The .java file does not need to reside in this directory for a servlet, but it is handy to keep the source in the same place.) Top level of WEB-INF.

39 Set-Up For First Web Application (cont.)
Once the classes directory looks like the one shown above. You are ready to invoke the servlet from a web browser. Start Tomcat and enter the URL Tomcat and the servlet will do the rest. If all goes well you should see the output that was shown on page 31. The classes directory


Download ppt "L.MARIA MICHAEL VISUWASAM UNIT-4"

Similar presentations


Ads by Google