how tomcat works.zip
NULL博文链接:https://sinly.iteye.com/blog/1454727different modules for processing. For example, the manager module is for processinguser sessions, the loader is for loading servlet classess, etcTomcat 4 and 5This book covers hoth tomcat 4 and 5. Here are some of the differences hetween thetwoTomcat 5 supports servlet 2. 1 and JSP 2.0 specifications, Tomcat 1 supportsServlet 2. 3 and JSP 1.2Tomcat 5 has a more efficient default connector than tomcat 4Tomcat 5 shares a thread for background processing whereas tomcat 4scomponents all have their own threads for background processing. ThereforeTOncal 5 uses less resources in this regard.Tomcat 5 does not need a mapper component to find a child componenttherefore simplifying the codeOverview of Each ChapterThere are 20 chapters in this book. The first two chapters serve as an introductionChapter l explains how an Http server works and Chapter 2 features a simpleservlet container. The next two chapters focus on the connector and Chapters 5 to20 cover each of the components in the container. The following is the summary ofcach of the chaptersNote For each chapter, there is an accompanying application similar to thecomponent being explainedChapter 1 starts this book by presenting a simple Http server To build a workingHttp server you need to know the internal workings of two classes in the java. netpackage: Socket and ServerSocket. There is sufficient background information in thischapter about these two classes for you to understand how the accompanyingapplication worksChapter 2 explains how simple servlet containers work. This chapter comes with twoservlet container applications that can service requests for static resources as wellas very simple servlets. In particular, you will learn how you can create request andresponse objects and pass them to the requested servlet s service method. There isalso a servlet that can be run inside the servlet containers and that you can invokefrom a web browserChapter 3 presents a simplified version of Tomcat 1s default connector. Theapplication built in this chapter serves as a learning tool to understand the connectordiscussed in Chapter 4Chapter 4 presents Tomcat 4s default connector. This connector has beendeprecated in favor of a faster connector called Coyote. Nevertheless, the defaultconnector is simpler and easier lo understandChapter 5 discusses the container module. A container is represented by theorg. apache. catalina Container interface and there are four types of containersengine, hosl, context, and wrapper. This chapter offers two applicalions thal workwith contexts and wrappersChapter 6 explains the Lifecycle interface. This interface defines the lifecycle of aCatalina component and provides an elegant way of notifying other components ofevents that occur in that component. In addition, the lifecycle interface provides anelegant mechanism for starting and stopping all the components in Catalina by onesingle start/stopChapter 7 covers loggers, which are components used for recording error messagesand other mes sagesChapter8 explains about loaders. A loader is an important Catalina moduleresponsible for loading servlet and other classes that a web application uses. Thischapter also shows how applicalion reloading is achievedChapter g discusses the manager, the component that manages sessions in sessionmanagement. It explains the various types of managers and how a manager canpersist session objects into a store. At the end of the chapter, you will learn how tobuild an application that uses a standardManager instance to run a servlet that usessession objects to store valuesChapter 10 covers web application security constraints for restricting access tocertain contents. You will learn entities related to security such as principals, roleslogin config, authenticators, etc. You will also write two applications that install anaulhenlicalor valve in the Standard Context objecl and uses basic authentication loauthenticate usersChapter ll explains in detail the org. apache. catalina. core. StandardWrapper classthat represents a servlet in a web application. In particular, this chapter explains howfilters and a servlets service method are invoked. The application accompanying thischapter uses StandardWrapper instances to represents servletsChapter 12 covers the org. apache. catalina. core. StandardContext class thatrepresents a web application. In particular this chapter discusses how aStandard context object is configured what happens in it for each incoming Httprequest, how it supports aut omatic reloading and how Tomcat 5 shares a thread thatexecutes periodic tasks in its associated componentsChapter 13 presents the two other containers: host and engine. You can also find thestandard implementation of these two containersorg. apache. catalina. core. StandardHost andorg. apache. catalina. core. StandardEngineChapter 14 offers the server and service components. A server provides an elegantstart and stop mechanism for the whole servlet container, a service serves as aholder for a container and one or more connectors The application accompanyingthis chapter shows how to use a server and a serviceChapters 15 explains the configuration of a web application through Digester,anexciting open source project from the Apache Software Foundation. For those notinitiated, this chapter presents a section that gently introduces the digester librarand how lo use it Lo convert the nodes in an XML docunent lo Java objects. Il chenexplains the Context Config object that configures a StandardContext instanceChapter 16 explains the shut down hook that Tomcat uses to always get a chance todo clean-up regardless how the user stops it (i. e. either appropriately by sending ashut down command or inappropriately by simply closing the console.Chapter l7 discusses the starting and stopping of Tomcat through the use of batchfiles and shell scriptsChapter 18 presents the deployer, the component responsible for deploying andinstalling web applicationsChapter 19 discusses a special interface, Container Servlet, to give a servlet accessto the Catalina internal objects. In particular, it discusses the manager applicationthat you can use to manage deployed applicationsChapter 20 discusses JMX and how Toncal mlake its internal objecTS Manageable bycreating MBeans for those objectsThe Application for Each ChapterEach chapter comes with one or more applications that focus on a specificcomponent in Catalina. Normally you ' ll find the simplified version of the componentbeing explained or code thal explains how lo use a Catalina component. All classesand interfaces in the chapters applications reside in the ex_chapternumber pyrmont package or its subpackages. For example, the classes in theapplication in Chapter l are part of the ex0l pyrmont packagePreparing the Prerequisite SoftwareThe applications accompanying this book run with J2SE version 1.4. The zippedsourcefilescanbedownloadedfromtheauthorswebsitewww.brainysoftware.comIt contains the source code for tomcat 4. 1. 12 and the applications used in this bookAssuming you have installed J2se 1. 4 and your path environment variable includesChe location of the jDK, follow these sleps:1. Extract the zip files. All extracted files will reside in a new directory calledHow TomcatWorks. How Tomcat Works is your working directory. There willbe several subdirecTories under HowToncaLWorks, including lib(conlainingall needed libraries), src(containing the source files), webroot(containing anHTML file and three sample servlets), and webapps (containing sampleapplications2. Change directory to the working directory and compile the java files. If youare using Windows, run the win-compile bat lile. If your computer is a Linuxmachine, type the following: (dont forget to chmod the file if necessary)/linux-compile shNote more information can be found in the readme. txt file included in the zip fileChapter 1: A Simple Web ServerThis chapter explains how Java web servers work. a web server is also called aHypertextTransferProtocol(http)serverbecauseituseshttptocommunicatewith its clients, which are usually web browsers. A Java-based web server uses twoimportant classes: java. net Socket and java. net. Server Socket, and communicationsare done through Http messages It is therefore natural to start this chapter with adiscussion of Http and the two classes afTerwards, it goes on to explain the simpleweb server application that accompanies this chapterTheHypertextTransferProtocol(http)Http is Che protocol Chat allows web servers and browsers lo send and receive dalaover the Internet. It is a request and response protocol. The client requests a fileand the server responds to the request Http uses reliable tcp connections-bydefault on tcp port 80. The first version of Http was Http/0.9, which was thenoverridden by Http/1.0. Replacing Http/1.0 is the current version of Http/1.1which is delined in Request for Comments(RFC)2616 and downloadable fromhttp://www.w3.org/protocols/httP/1.1/rfc2616.pdfNoteThissectioncovershttp1.1onlybrieflyandisintendedtohelpyouunderstand the Messages sent by web server applicalions. If you are interestedin more details. read rfc 2616In Http it is always the client who initiates a transaction by establishing aconnection and sending an Http request The web server is in no posilion locontact a client or make a callback connection to the client. Either the client or theserver can prematurely terminate a connection. For example, when using a webbrowser you can click the Stop button on your browser to stop the download processofafileeffectivelyclosingthehttpconnectionwiththewebserverHttp RequestsAnhttprequestconsistsofthreecomponentsMethod-Uniform Resource Identifier(URI-Protocol/ VersionRequest headersEntity bodyAn example of an Http request is the followingPosT /exAmpleS/default.jsp Http/1.1Accept: text/plain; text/htmlAcccot-Language: en-ghConnec-ion Keep-AliveHost: localhost-User-Agent: Mozilla/4.0(compatible; MSIE 4.0l; Windows 98)Conten--Type: application/x-wwW-form-urlcncodedAccept-Encoding: gzip, deflatelastName=franks&firstName=MichaelThe nethod-URI-prolocol version appears as the first line of the request.POST /examples/default. jsp ITTP/1.1where POSt is the request method, /examples/ default. jsp represents the URI andHttp/1.1 the Protocol/version sectionEachhttprequestcanuseonleofthemlanyrequestMethodsasspeciliedintheHttp standards The Http 1. 1 supports seven types of request Get, Post,HEAD, OPTIONS, PUT, DELETE and TRACe. get and post are the mostcommonly used in Internet applicationsThe URI specifies an Internet resource completely. A URI is usually interpreted asbeing relative to the servers root directory Thus, it should always begin with aforward slash / A Uniform Resource Locator (url) is actually a type of URI (seehttp://www.ietf.org/rfc/rfc2396.txt).TheprotocolversionrepresentstheversionofthehttpprotocolbeingusedThe request header contains useful information about the client environment and theentity body of the request. For example, it could contain the language the browser isset for, the length of the entity body, and so on. Each header is separaled by acarriage return/linefeed(CRLF) sequenceBetween the headers and the entity body there is a blank line(CrlF)that isinportantlothehttprequestforllal.TheCrlftellschehttpserverwheretheentity body begins. In some Internet programming books, this CrlF is consideredthefourthcomponentofanhttprequestIntheprevioushttprequesttheentitybodyissimplythefollowinglinelastName=Franks&firstName=MichaelTheentitybodycaneasilybecomemuchlongerinatypicalhttprequestHttp ResponsesSimilartoanhttprequestanhttpresponsealsoconsistsofthreepartsProlocol-Stalus code-DescriptionResponse headersEntity bodyThefollowingisanexampleofanhttpresponseHttp/1.1200OkServer: Microsc=t-IIS/4. 0200413Conten--Type: ext/htmlLast-Mcdified: M5Jan20413:13:12GMTConten= th: 112headliTTe Response Example Welcome to Brainy Software body>The first line of the response header is similar lo the first line of the request headerThefirstlinetellsyouthattheprotocolusedishttpversion1.1,therequestsucceeded(200=Success), and thal everything went okayThe response headers contain useful informalion similar lo the headers in the requestThe entity body of the response is the html content of the response itself. Theheaders and the entity body are separated by a sequence of crlFThe Socket classA socket is an endpoint of a network connection. A socket enables an application toread from and write to the network. two software applications residing on twodifferent computers can communicate with each other by sending and receiving bytestreams over a connection To send a message from your application to anotherapplication, you need to know the ip address as well as the port number of the socketof the other application. In Java, a socket is represented by the java. net. SocketclassTo create a socket, you can use one of the many constructors of the Socket classOne of these constructors accepts the host name and the port numberpublic Socket (java. l ang String host, int. port)where hosl is Che remole machine name or IP address and port is the port number ofthe remote application for example, to connect to yahoo. com at port 80, you wouldconstruct the following Socket objectnew Socket ("yahoo. com",80Once you create an instance of the Socket class successfully you can use it to sendand receive streams of bytes. To send byte streams, you must first call the Socketclass's getCutputS-ream method lo obtain d java. io Outputstream objecl. To sendtext to a remote application, you often want to construct a java.ioPrintwriterobject from the OutputStream object returned. To receive byte streams from theother end of the connection, you call the Socket classs getInputstream method thatreturns a java. io. InoutstreamThefollowingcodesnippetcreatesasocketthatcancommunicatewithalocalHTTPserver(127.0.0.1denotesalocalhost),sendsanhttprequestandreceivestheresponse from the server. It creates a stringBuffer object to hold the response andprints it on the consoleSocket socket= new socket(127.0.0.l",8080)iOutputstream os= socket getoutputstream()iboolean autoflush =tPrintwriter out new Printnritersocket getOut p: tStream(), autoflush)iBufferedReader in =new Bufferedreader(new InputStrcamRcadcr( socket. gctInputstrcam()))i// send an Http request to the web serverout println("GeT /index. jsp IITP/1.1")iout printin(ost: localhost: 8080)iConnection: C1t-n()redboolean loop - truStringBuffer sb= new String Buffer (8C96);hile (loop)(三(i:.eady()){int i=0
下载地址
用户评论