Servlet和JSP技术简述(英文翻译)

合集下载

servlet概述

servlet概述

servlet概述1 什么是servlet? Servlet 是基于 Java 技术的 web 组件,容器托管的,⽤于⽣成动态内容。

像其他基于 Java 的组件技术⼀样,Servlet 也是基于平台⽆关的 Java 类格式,被编译为平台⽆关的字节码,可以被基于 Java 技术的 web server动态加载并运⾏。

Servlet是⼀种容器,有时候也叫做 servlet 引擎,是 web server 为⽀持 servlet 功能扩展的部分。

客户端通过 Servlet 容器实现的请求/应答模型与 Servlet 交互。

2 什么是servlet容器? Servlet 容器是 web server 或 application server 的⼀部分,提供基于请求/响应发送模型的⽹络服务,解码基于 MIME 的请求,并且格式化基于 MIME 的响应。

Servlet 容器也包含了管理 Servlet ⽣命周期。

Servlet 容器可以嵌⼊到宿主的 web server 中,或者通过 Web Server 的本地扩展 API 单独作为附加组件安装。

Servelt 容器也可能内嵌或安装到包含 web 功能的 application server 中。

所有 Servlet 容器必须⽀持基于 HTTP 协议的请求/响应模型,⽐如像基于 HTTPS(HTTP over SSL)协议的请求/应答模型可以选择性的⽀持。

容器必须实现的 HTTP 协议版本包含 HTTP/1.0 和 HTTP/1.1。

因为容器或许⽀持 RFC2616 (HTTP/1.1)描述的缓存机制,缓存机制可能在将客户端请求交给 Servlet 处理之前修改它们,也可能在将Servlet ⽣成的响应发送给客户端之前修改它们,或者可能根据 RFC2616 规范直接对请求作出响应⽽不交给 Servlet 进⾏处理。

Servlet 容器应该使 Servlet 执⾏在⼀个安全限制的环境中。

JSP技术简介

JSP技术简介

第1章JSP技术简介JSP(Java Server Pages)技术是由Sun公司发布的用于开发动态Web应用的一项技术。

它以其简单易学、跨平台的特性,在众多动态Web应用程序设计语言中异军突起,在短短几年中已经形成了一套完整的规范,并广泛地应用于电子商务等各个领域中。

在国内,JSP 现在也得到了比较广泛的重视,得到了很好的发展,越来越多的动态网站开始采用JSP技术。

本章就对JSP及其相关技术进行简单的介绍。

1.1 认识HTTP协议HTTP协议(Hypertext Transfer Protocol,超文本传送协议)是WWW服务器使用的主要协议,对HTTP协议细节的基本理解是编写JSP或Java小程序的开发人员所必需的。

因此在学习JSP技术之前有必要更加仔细地研究一下HTTP消息的格式(这里的讨论源自HTTP/1.1协议规范。

参见规范2616,网址为/rfc/rfc2616.txt)。

HTTP 协议的关键部分有HTTP请求和HTTP响应,以及客户端Web程序设计的一些基础知识,在第4章4.4节将会具体介绍。

1.2 客户端Web程序设计介绍Web浏览器现已成为深受大多数用户喜爱的用户界面。

HTML语言提供了丰富的控件,第三方厂商提供了Visual Basic编写的数百个额外的控件,这些都使得Web浏览器独具特色。

虽然Web浏览器与传统的GUI界面有一定的差距,但它提供了一种独立而又简单的方法来访问分布式资源,尤其是Internet资源。

而且越来越多的客户端Web程序扩展技术变得更加成熟,出现了包括CSS、JavaScript、VBScript、动态HTML、Java1.1.Applet应用程序等技术在内的客户端Web程序设计技术,它们的相互结合使得Web程序更加迷人。

下面简单介绍几种常用的客户端Web程序设计技术的特点。

本书假定读者对这些技术都有一定的了解,不对这些技术作详细介绍。

1.2.1 CSSCSS(Cascading Style Sheets)称为层叠样式表,是动态HTML技术的一个部分,但可以和HTML结合使用。

jsp技术网站设计外文翻译--将Servlet和JSP组合使用

jsp技术网站设计外文翻译--将Servlet和JSP组合使用

Combining JSP and ServletsThe technology of JSP and Servlet is the most important technology which use Java technology to exploit request of server, and it is also the standard which exploit business application .Java developers prefer to use it for a variety of reasons, one of which is already familiar with the Java language for the development of this technology are easy to learn Java to the other is "a preparation, run everywhere" to bring the concept of Web applications, To achieve a "one-prepared everywhere realized." And more importantly, if followed some of the principles of good design, it can be said of separating and content to create high-quality, reusable, easy to maintain and modify the application. For example, if the document in HTML embedded Java code too much (script), will lead the developed application is extremely complex, difficult to read, it is not easy reuse, but also for future maintenance and modification will also cause difficulties. In fact, CSDN the JSP / Servlet forum, can often see some questions, the code is very long, can logic is not very clear, a large number of HTML and Java code mixed together. This is the random development of the defects.Early dynamic pages mainly CGI (Common Gateway Interface, public Gateway Interface) technology, you can use different languages of the CGI programs, such as VB, C / C + + or Delphi, and so on. Though the technology of CGI is developed and powerful, because of difficulties in programming, and low efficiency, modify complex shortcomings,it is gradually being replaced by the trend. Of all the new technology, JSP / Servlet with more efficient and easy to program, more powerful, more secure and has a good portability, they have been many people believe that the future is the most dynamic site of the future development of technology.Similar to CGI, Servlet support request / response model. When a customer submit a request to the server, the server presented the request Servlet, Servlet responsible for handling requests and generate a response, and then gave the server, and then from the server sent to the customer. And the CGI is different, Servlet not generate a new process, but with HTTP Server at the same process. It threads through the use of technology, reduce the server costs. Servlet handling of the request process is this: When received from the client's request, calling service methods, the method of Servlet arrival of the first judgement is what type of request (GET / POST / HEAD…), then calls the appropriate treatment (DoGet / doP ost / doHead…) and generate a response.Although such a complex, in fact, simply said to Servlet is a Java class. And the general category of the difference is that this type operating in a Servlet container, which can provide session management and targeted life-cycle management. So that when you use the Servlet, you can get all the benefits of the Java platform, including the safety of the management, use JDBC access the database and cross-platform capability. Moreover, Servlet using thread, and can develop more efficient Web applications.JSP technology is a key J2EE technology, it at a higher level of abstraction of a Servlet.It allows conventional static and dynamic HTML content generated by combining an HTML page looks like, but as a Servlet to run. There are many commercial application server support JSP technology, such as BEA WebLogic, IBM WebSphere, JRun, and so on. JSP and Servlet use more than simple. If you have a JSP support for Web servers, and a JSP document, you can put it Fangdao any static HTML files can be placed, do not have to compile, do not have to pack, do not have to ClassPath settings, you can visit as ordinary Web It did visit, the server will automatically help you to do other work.JSP document looks like an ordinary static HTML document, but inside contains a number of Java code. It uses. Jsp the suffix, used to tell the server this document in need of special treatment. When we visit a JSP page, the document will first be translated into a JSP engine Java source files, is actually a Servlet, and compiler, and then, like other Servlet, from Servlet engine to handle. Servlet engine of this type loading, handling requests from customers, and the results returned to the customer, as shown below:Figure 1: Calling the process of JSP pagesAfter another visit this page to the customer, as long as the paper there have been no changes, JSP engine has been loaded directly call the Servlet. If you have already been modified, it will be once again the implementation of the above process, translate, compile and load. In fact, this is the so-called "first person to punishment." Because when the first visit to the implementation of a series of the above process, so will spend some time after such a visit would not.Java servlets offer a powerful API that provides access to all the information about the request, the session, and the application. combining JSP with servlets lets you clearly separate the application logic from the presentation of the application; in other words, it lets you use the most appropriate component type for the roles of Model, View and Controller.Servlets, Filters, and ListenersA servlet is a Java class that extends a server with functionality for processing a request and producing a response. It's implemented using the classes and interfaces defined by the Servlet API. The API consists of two packages: the javax.servlet package contains classes and interfaces that are protocol-independent, while the javax.servlet.http package provides HTTP-specific extensions and utility classes.What makes a servlet a servlet is that the class implements an interface named javax.servlet.Servlet, either directly or by extending one of the support classes. This interface defines the methods used by the web container to manage and interact with theservlet. A servlet for processing HTTP requests typically extends the javax.servlet.http.HttpServlet class. This class implements the Servlet interface and provides additional methods suitable for HTTP processing.Servlet LifecycleThe web container manages all aspects of the servlet's lifecycle. It creates an instance of the servlet class when needed, passes requests to the instance for processing, and eventually removes the instance. For an HttpServlet, the container calls the following methods at the appropriate times in the servlet lifecycle.Besides the doGet( ) and doPost( ) methods, there are methods corresponding to the other HTTP methods: doDelete( ), doHead( ), doOptions( ), doPut( ), and doTrace( ). Typically you don't implement these methods; the HttpServlet class already takes care of HEAD, OPTIONS, and TRACE requests in a way that's suitable for most servlets, and the DELETE and PUT HTTP methods are rarely used in a web application.It's important to realize that the container creates only one instance of each servlet. This means that the servlet must be thread safe -- able to handle multiple requests at the same time, each executing as a separate thread through the servlet code. Without getting lost in details, you satisfy this requirement with regards to instance variables if you modify the referenced objects only in the init( ) and destroy( ) methods, and just read them in the request processing methods.Compiling and Installing a ServletTo compile a servlet, you must first ensure that you have the JAR file containing all Servlet API classes in the CLASSPATH environment variable. The JAR file is distributed with all web containers. Tomcat includes it in a file called servlet.jar, located in the common/lib directory. On a Windows platform, you include the JAR file in the CLASSPATH.. Reading a RequestOne of the arguments passed to the doGet( ) and doPost( ) methods is an object that implements the HttpServletRequest interface. This interface defines methods that provide access to a wealth of information about the request.Generating a ResponseBesides the request object, the container passes an object that implements the HttpServletResponse interface as an argument to the doGet( ) and doPost( ) methods. This interface defines methods for getting a writer or stream for the response body. It also defines methods for setting the response status code and headers.Using Filters and ListenersThe servlet specification defines two component types beside servlets: filters and listeners. These two types were introduced in the Servlet 2.3 specification, so if you're using a container that doesn't yet support this version of the specification, I'm afraid you'reout of luck.FiltersA filter is a component that can intercept a request targeted for a servlet, JSP page, or static page, as well as the response before it's sent to the client. This makes it easy to centralize tasks that apply to all requests, such as access control, logging, and charging for the content or the services offered by the application. A filter has full access to the body and headers of the request and response, so it can also perform various transformations. One example is compressing the response body if the Accept-Language request header indicates that the client can handle a compressed response.A filter can be applied to either a specific servlet or to all requests matching a URL pattern, such as URLs starting with the same path elements or having the same extension. ListenersListeners allow your application to react to certain events. Prior to Servlet 2.3, you could handle only session attribute binding events (triggered when an object was added or removed from a session). You could do this by letting the object saved as a sessionattribute(using the HttpSession.setAttribute() method)implement the HttpSessionBindingListener interface. With the new interfaces introduced in the 2.3 version of the specification, you can create listeners for servlet context and session lifecycle events as well as session activation and passivation events (used by a container that temporarily saves session state to disk or migrates a session to another server). A newsession attribute event listener also makes it possible to deal with attribute binding events for all sessions in one place, instead of placing individual listener objects in each session.The new types of listeners follow the standard Java event model. In other words, a listener is a class that implements one or more of the listener interfaces. The interfaces define methods that correspond to events. The listener class is registered with the container when the application starts, and the container then calls the event methods at the appropriate times.Initializing Shared Resources Using a ListenerBeans like this typically need to be initialized before they can be used. For instance, they may need a reference to a database or some other external data source and may create an initial information cache in memory to provide fast access even to the first request for data. You can include code for initialization of the shared resources in the servlet and JSP pages that need them, but a more modular approach is to place all this code in one place and let the other parts of the application work on the assumption that the resources are already initialized and available. An application lifecycle listener is a perfect tool for this type of resource initialization. This type of listener implements the javax.servlet.ServletContextListener interface, with methods called by the container when the application starts and when it shuts down.Picking the Right Component Type for Each TaskThe Project Billboard application introduced is a fairly complex application. Half thepages are pure controller and business logic processing, it accesses a database to authenticate users, and most pages require access control. In real life, it would likely contain even more pages, for instance, pages for access to a shared document archive, time schedules, and a set of pages for administration. As the application evolves, it may become hard to maintain as a pure JSP application. It's easy to forget to include the access control code in new pages.This is clearly an application that can benefit from using a combination of JSP pages and the component types defined by the servlet specification for the MVC roles. Let's look at the main requirements and see how we can map them to appropriate component types:●Database access should be abstracted, to avoid knowledge of a specific dataschema or database engine in more than one part of the application: beans in therole of Model can be used to accomplish this.●The database access beans must be made available to all other parts of theapplication when it starts: an application lifecycle event listener is the perfectcomponent type for this task.●Only authenticated users must be allowed to use the application: a filter canperform access control to satisfy this requirement.●Request processing is best done with Java code: a servlet, acting as the Controller,fits the bill.●It must be easy to change the presentation: this is where JSP shines, acting as theView.Adding servlets, listeners, and filters to the mix minimizes the need for complex logic in the JSP pages. Placing all this code in Java classes instead makes it possible to use a regular Java compiler and debugger to fix potential problems.Centralized Request Processing Using a ServletWith a servlet as the common entry point for all application requests, you gain control over the page flow of the application. The servlet can decide which type of response to generate depending on the outcome of the requested action, such as returning a common error page for all requests that fail, or different responses depending on the type of client making the request. With the help from some utility classes, it can also provide services such as input validation, I18N preparations, and in general, encourage a more streamlined approach to request handling.When you use a servlet as a Controller, you must deal with the following basic requirements:●All requests for processing must be passed to the single Controller servlet.●The servlet must be able to distinguish requests for different types of processing.Here are other features you will want support for, even though they may not be requirements for all applications:● A strategy for extending the application to support new types of processingA mechanism for changing the page flow of the application without modifyingcode.Mapping Application Requests to the ServletThe first requirement for using a Controller servlet is that all requests must pass through it. This can be satisfied in many ways. If you have played around a bit with servlets previously, you're probably used to invoking a servlet with a URI that starts with /myApp/servlet. This is a convention introduced by Suns Java Web Server (JWS), the first product to support servlets before the API was standardized. Most servlet containers support this convention today, even though it's not formally defined in the servlet specification.将Servlet和JSP组合使用Servlet和JSP技术是用Java开发服务器端应用的主要技术,是开发商务应用表示端的标准。

外文翻译---JSP的技术发展历史

外文翻译---JSP的技术发展历史

THE TECHNIQUE DEVELOPMENT HISTORY OF JSPBy:Kathy Sierra and Bert BatesSource:Servlet&JSPThe Java Server Pages( JSP) is a kind of according to web of the script plait distance technique, similar carries the script language of Java in the server of the Netscape company of server- side JavaScript( SSJS) and the Active Server Pages(ASP) of the Microsoft. JSP compares the SSJS and ASP to have better can expand sex, and it is no more exclusive than any factory or some one particular server of Web. Though the norm of JSP is to be draw up by the Sun company of, any factory can carry out the JSP on own system.The After Sun release the JSP( the Java Server Pages) formally, the this kind of new Web application development technique very quickly caused the people's concern. JSP provided a special development environment for the Web application that establishes the high dynamic state. According to the Sun parlance, the JSP can adapt to include the Apache WebServer, IIS4.0 on the market at inside of 85% server product.This chapter will introduce the related knowledge of JSP and Databases, and JavaBean related contents, is all certainly rougher introduction among them basic contents, say perhaps to is a Guide only, if the reader needs the more detailed information, pleasing the book of consult the homologous JSP.1.1 GENERALIZEThe JSP(Java Server Pages) is from the company of Sun Microsystems initiate, the many companies the participate to the build up the together of the a kind the of dynamic the state web the page technique standard, the it have the it in the construction the of the dynamic state the web page the strong but the do not the especially of the function. JSP and the technique of ASP of the Microsoft is very alike. Both all provide the ability that mixes with a certain procedure code and is explain by the language engine to carry out the procedure code in the code of HTML. Underneath we are simple of carry on the introduction to it.JSP pages are translated into servlets. So, fundamentally, any task JSP pages can perform could also be accomplished by servlets. However, this underlying equivalence does not mean that servlets and JSP pages are equally appropriate in all scenarios. The issue is not the power of the technology, it is the convenience, productivity, and maintainability of one or the other. After all, anything you can do on a particular computer platform in the Java programming language you could also do in assembly language. But it still matters which you choose.JSP provides the following benefits over servlets alone:• It is easier to write and maintain the HTML. Your static code is ordinary HTML: no extra backslashes, no double quotes, and no lurking Java syntax.• You can use standard Web-site development tools. Even HTML tools that know nothing about JSP can be used because they simply ignore the JSP tags.• You can divide up your development team. The Java programmers can work on the dynamic code. The Web developers can concentrate on the presentation layer. On large projects, this division is very important. Depending on the size of your team and the complexity of your project, you can enforce a weaker or stronger separation between the static HTML and the dynamic content.Now, this discussion is not to say that you should stop using servlets and use only JSP instead. By no means. Almost all projects will use both. For some requests in your project, you will use servlets. For others, you will use JSP. For still others, you will combine them with the MVC architecture . You want the appropriate tool for the job, and servlets, by themselves, do not complete your toolkit.1.2 SOURCE OF JSPThe technique of JSP of the company of Sun, making the page of Web develop the personnel can use the HTML perhaps marking of XML to design to turn the end page with format. Use the perhaps small script future life of marking of JSP becomes the dynamic state on the page contents.( the contents changes according to the claim of)The Java Servlet is a technical foundation of JSP, and the large Web applies the development of the procedure to need the Java Servlet to match with with the JSP and then can complete, this name of Servlet comes from the Applet, the local translation method of now is a lot of, this book in order not to misconstruction, decide the direct adoption Servlet but don't do any translation, if reader would like to, can call it as" small service procedure". The Servlet is similar to traditional CGI, ISAPI, NSAPI etc. Web procedure development the function of the tool in fact, at use the Java Servlet hereafter, the customer need not use again the lowly method of CGI of efficiency, also need not use only the ability come to born page of Web of dynamic state in the method of API that a certain fixed Web server terrace circulate. Many servers of Web all support the Servlet, even not support the Servlet server of Web directly and can also pass the additional applied server and the mold pieces to support the Servlet. Receive benefit in the characteristic of the Java cross-platform, the Servlet is also a terrace irrelevant, actually, as long as match the norm of Java Servlet, the Servlet is complete to have nothing to do with terrace and is to have nothing to do with server of Web. Because the Java Servlet is internal to provide the service by the line distance, need not start a progressto the each claimses, and make use of the multi-threading mechanism can at the same time for several claim service, therefore the efficiency of Java Servlet is very high.But the Java Servlet also is not to has no weakness, similar to traditional CGI, ISAPI, the NSAPI method, the Java Servlet is to make use of to output the HTML language sentence to carry out the dynamic state web page of, if develop the whole website with the Java Servlet, the integration process of the dynamic state part and the static state page is an evil-foreboding dream simply. For solving this kind of weakness of the Java Servlet, the SUN released the JSP.A number of years ago, Marty was invited to attend a small 20-person industry roundtable discussion on software technology. Sitting in the seat next to Marty was James Gosling, inventor of the Java programming language. Sitting several seats away was a high-level manager from a very large software company in Redmond, Washington. During the discussion, the moderator brought up the subject of Jini, which at that time was a new Java technology. The moderator asked the manager what he thought of it, and the manager responded that it was too early to tell, but that it seemed to be an excellent idea. He went on to say that they would keep an eye on it, and if it seemed to be catching on, they would follow his company's usual "embrace and extend" strategy. At this point, Gosling lightheartedly interjected "You mean disgrace and distend."Now, the grievance that Gosling was airing was that he felt that this company would take technology from other companies and suborn it for their own purposes. But guess what? The shoe is on the other foot here. The Java community did not invent the idea of designing pages as a mixture of static HTML and dynamic code marked with special tags. For example, Cold Fusion did it years earlier. Even ASP (a product from the very software company of the aforementioned manager) popularized this approach before JSP came along and decided to jump on the bandwagon. In fact, JSP not only adopted the general idea, it even used many of the same special tags as ASP did.The JSP is an establishment at the model of Java servlets on of the expression layer technique, it makes the plait write the HTML to become more simple.Be like the SSJS, it also allows you carry the static state HTML contents and servers the script mix to put together the born dynamic state exportation. JSP the script language that the Java is the tacit approval, however, be like the ASP and can use other languages( such as JavaScript and VBScript), the norm of JSP also allows to use other languages.1.3JSP CHARACTERISTICSIs a service according to the script language in some one language of the statures system this kind of discuss, the JSP should be see make is a kind of script language.However, be a kind of script language, the JSP seemed to be too strong again, almost can use all Javas in the JSP.Be a kind of according to text originally of, take manifestation as the central development technique, the JSP provided all advantages of the Java Servlet, and, when combine with a JavaBeans together, providing a kind of make contents and manifestation that simple way that logic separate. Separate the contents and advantage of logical manifestations is, the personnel who renews the page external appearance need not know the code of Java, and renew the JavaBeans personnel also need not be design the web page of expert in hand, can use to take the page of JavaBeans JSP to define the template of Web, to build up a from have the alike external appearance of the website that page constitute. JavaBeans completes the data to provide, having no code of Java in the template thus, this means that these templates can be written the personnel by a HTML plait to support. Certainly, can also make use of the Java Servlet to control the logic of the website, adjust through the Java Servlet to use the way of the document of JSP to separate website of logic and contents.Generally speaking, in actual engine of JSP, the page of JSP is the edit and translate type while carry out, not explain the type of. Explain the dynamic state web page development tool of the type, such as ASP, PHP3 etc., because speed etc. reason, have already can't satisfy current the large electronic commerce needs appliedly, traditional development techniques are all at to edit and translate the executive way change, such as the ASP → ASP+;PHP3 → PHP4.In the JSP norm book, did not request the procedure in the JSP code part( be called the Scriptlet) and must write with the Java definitely. Actually, have some engines of JSP are adoptive other script languages such as the EMAC- Script, etc., but actually this a few script languages also are to set up on the Java, edit and translate for the Servlet to carry out of. Write according to the norm of JSP, have no Scriptlet of relation with Java also is can of, however, mainly lie in the ability and JavaBeans, the Enterprise JavaBeanses because of the JSP strong function to work together, so even is the Scriptlet part not to use the Java, edit and translate of performance code also should is related with Java.1.4JSP MECHANISMTo comprehend the JSP how unite the technical advantage that above various speak of, come to carry out various result easily, the customer must understand the differentiation of" the module develops for the web page of the center" and" the page develops for the web page of the center" first.The SSJS and ASP are all in several year ago to release, the network of that time is still very young, no one knows to still have in addition to making all business, datas and theexpression logic enter the original web page entirely heap what better solve the method. This kind of model that take page as the center studies and gets the very fast development easily. However, along with change of time, the people know that this kind of method is unwell in set up large, the Web that can upgrade applies the procedure. The expression logic write in the script environment was lock in the page, only passing to shear to slice and glue to stick then can drive heavy use. Express the logic to usually mix together with business and the data logics, when this makes be the procedure member to try to change an external appearance that applies the procedure but do not want to break with its llied business logic, apply the procedure of maintenance be like to walk the similar difficulty on the eggshell. In fact in the business enterprise, heavy use the application of the module already through very mature, no one would like to rewrite those logics for their applied procedure.HTML and sketch the designer handed over to the implement work of their design the Web plait the one who write, make they have to double work- Usually is the handicraft plait to write, because have no fit tool and can carry the script and the HTML contents knot to the server to put together. Chien but speech, apply the complexity of the procedure along with the Web to promote continuously, the development method that take page as the center limits sex to become to get up obviously.At the same time, the people always at look for the better method of build up the Web application procedure, the module spreads in customer's machine/ server the realm. JavaBeans and ActiveX were published the company to expand to apply the procedure developer for Java and Windows to use to come to develop the complicated procedure quickly by" the fast application procedure development"( RAD) tool. These techniques make the expert in the some realm be able to write the module for the perpendicular application plait in the skill area, but the developer can go fetch the usage directly but need not control the expertise of this realm.Be a kind of take module as the central development terrace, the JSP appeared. It with the JavaBeans and Enterprise JavaBeans( EJB) module includes the model of the business and the data logic for foundation, provide a great deal of label and a script terraces to use to come to show in the HTML page from the contents of JavaBeans creation or send a present in return. Because of the property that regards the module as the center of the JSP, it can drive Java and not the developer of Java uses equally. Not the developer of Java can pass the JSP label( Tags) to use the JavaBeans that the deluxe developer of Java establish. The developer of Java not only can establish and use the JavaBeans, but also can use the language of Java to come to control more accurately in the JSP page according to the expression logic of the first floor JavaBeans.See now how JSP is handle claim of HTTP. In basic claim model, a claim directly was send to JSP page in. The code of JSP controls to carry on hour of the logic processing and module of JavaBeanses' hand over with each other, and the manifestation result in dynamic state bornly, mixing with the HTML page of the static state HTML code. The Beans can be JavaBeans or module of EJBs. Moreover, the more complicated claim model can see make from is request other JSP pages of the page call sign or Java Servlets.The engine of JSP wants to chase the code of Java that the label of JSP, code of Java in the JSP page even all converts into the big piece together with the static state HTML contents actually. These codes piece was organized the Java Servlet that customer can not see to go to by the engine of JSP, then the Servlet edits and translate them automatically byte code of Java.Thus, the visitant that is the website requests a JSP page, under the condition of it is not knowing, an already born, the Servlet actual full general that prepared to edit and translate completes all works, very concealment but again and efficiently. The Servlet is to edit and translate of, so the code of JSP in the web page does not need when the every time requests that page is explain. The engine of JSP need to be edit and translate after Servlet the code end is modify only once, then this Servlet that editted and translate can be carry out. The in view of the fact JSP engine auto is born to edit and translate the Servlet also, need not procedure member begins to edit and translate the code, so the JSP can bring vivid sex that function and fast developments need that you are efficiently.Compared with the traditional CGI, the JSP has the equal advantage. First, on the speed, the traditional procedure of CGI needs to use the standard importation of the system to output the equipments to carry out the dynamic state web page born, but the JSP is direct is mutually the connection with server. And say for the CGI, each interview needs to add to add a progress to handle, the progress build up and destroy by burning constantly and will be a not small burden for calculator of be the server of Web. The next in order, the JSP is specialized to develop but design for the Web of, its purpose is for building up according to the Web applied procedure, included the norm and the tool of a the whole set. Use the technique of JSP can combine a lot of JSP pages to become a Web application procedure very expediently.JSP的技术发展历史作者:Kathy Sierra and Bert Bates来源:Servlet&JSPJava Server Pages(JSP)是一种基于web的脚本编程技术,类似于网景公司的服务器端Java脚本语言——server-side JavaScript(SSJS)和微软的Active Server Pages(ASP)。

jsp+servlet+jdbc实现对数据库的增删改查

jsp+servlet+jdbc实现对数据库的增删改查

jsp+servlet+jdbc实现对数据库的增删改查⼀、JSP和Servlet的简单介绍1、Servlet和JSP简介:Java开发Web应⽤程序时⽤到的技术主要有两种,即Servlet和JSP,Servlet是在服务器端执⾏的Java程序,⼀个被称为Servlet容器的程序(其实就是服务器)负责执⾏Java程序,⽽JSP(Java Server Page)则是⼀个页⾯,由JSP容器负责执⾏.2、Servlet和JSP的区别:Servlet以Java程序为主,输出HTML代码时需要使⽤out.println函数,也就是说Java中内嵌HTML;⽽JSP则以HTML页⾯为主,需要写Java代码时则在页⾯中直接插⼊Java代码,即HTML中内嵌Java.3、MVC模型MVC模型就是将数据、逻辑处理、⽤户界⾯分离的⼀种⽅法1)、M(Model, 模型):⽤于数据处理、逻辑处理2)、V(View,视图):⽤于显⽰⽤户界⾯3)、C(Controller,控制器):根据客户端的请求控制逻辑⾛向和画⾯⽽在Java中,MVC这三个部分则分别对应于 JavaBeans、JSP和Servlet1)、M = JavaBeans:⽤于传递数据,拥有与数据相关的逻辑处理2)、V = JSP:从Model接收数据并⽣成HTML3)、C = Servlet:接收HTTP请求并控制Model和View4、jdbc连接,可参考⽂章:⼆、代码演⽰,实现了book的添加删除和修改功能1、环境的配置myeclipse+tomcat+MySQL2、Book中bean类package example.bean.book;public class Book {// 编号private int id;// 图书名称private String name;// 价格private double price;// 数量private int bookCount;// 作者private String author;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) { = name;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}public int getBookCount() {return bookCount;}public void setBookCount(int bookCount) {this.bookCount = bookCount;}public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}}3、Servlet类1)、FindServlet.javapackage example.servlet.book;import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;import java.util.ArrayList;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import example.bean.book.Book;/*** Servlet implementation class FindServlet*/public class FindServlet extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse* response)*/protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {try {// 加载数据库驱动,注册到驱动管理器Class.forName("com.mysql.jdbc.Driver");// 数据库连接字符串String url = "jdbc:mysql://localhost:3306/db_book?useUnicode=true&characterEncoding=utf-8"; // 数据库⽤户名String username = "root";// 数据库密码String password = "";// 创建Connection连接Connection conn = DriverManager.getConnection(url, username,password);// 添加图书信息的SQL语句String sql = "select * from tb_books";// 获取StatementStatement statement = conn.createStatement();ResultSet resultSet = statement.executeQuery(sql);List<Book> list = new ArrayList<Book>();while (resultSet.next()) {Book book = new Book();book.setId(resultSet.getInt("id"));book.setName(resultSet.getString("name"));book.setPrice(resultSet.getDouble("price"));book.setBookCount(resultSet.getInt("bookCount"));book.setAuthor(resultSet.getString("author"));list.add(book);}request.setAttribute("list", list);resultSet.close();statement.close();conn.close();} catch (Exception e) {e.printStackTrace();}request.getRequestDispatcher("book_list.jsp").forward(request, response);}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse* response)*/protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}2)、UpdateServlet.java类package example.servlet.book;import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/*** Servlet implementation class UpdateServlet*/public class UpdateServlet extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse* response)*/protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {int id = Integer.valueOf(request.getParameter("id"));int bookCount = Integer.valueOf(request.getParameter("bookCount"));try {// 加载数据库驱动,注册到驱动管理器Class.forName("com.mysql.jdbc.Driver");// 数据库连接字符串String url = "jdbc:mysql://localhost:3306/db_book";// 数据库⽤户名String username = "root";// 数据库密码String password = "";// 创建Connection连接Connection conn = DriverManager.getConnection(url, username,password);// 更新SQL语句String sql = "update tb_books set bookcount=? where id=?";// 获取PreparedStatementPreparedStatement ps = conn.prepareStatement(sql);// 对SQL语句中的第⼀个参数赋值ps.setInt(1, bookCount);// 对SQL语句中的第⼆个参数赋值ps.setInt(2, id);// 执⾏更新操作ps.executeUpdate();// 关闭PreparedStatementps.close();// 关闭Connectionconn.close();e.printStackTrace();}// 重定向到FindServletresponse.sendRedirect("FindServlet");}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse* response)*/protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}3)、DeleteServlet类package example.servlet.book;import java.io.IOException;import java.sql.Connection;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import example.dao.book.BookJdbcDao;import example.dao.book.ConnectionFactory;/*** Servlet implementation class DeleteServlet*/public class DeleteServlet extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse* response)*/protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {int id = Integer.valueOf(request.getParameter("id"));try {// // 加载数据库驱动,注册到驱动管理器// Class.forName("com.mysql.jdbc.Driver");// // 数据库连接字符串// String url = "jdbc:mysql://localhost:3306/db_book";// // 数据库⽤户名// String username = "root";// // 数据库密码// String password = "";// // 创建Connection连接// Connection conn = DriverManager.getConnection(url, username,// password);// // 删除图书信息的SQL语句// String sql = "delete from tb_books where id=?";// // 获取PreparedStatement// PreparedStatement ps = conn.prepareStatement(sql);// // 对SQL语句中的第⼀个占位符赋值// ps.setInt(1, id);// // 执⾏更新操作// ps.executeUpdate();// // 关闭PreparedStatement// ps.close();// // 关闭Connection// conn.close();BookJdbcDao bookDao=new BookJdbcDao();Connection conn=ConnectionFactory.getInstance().getConnection();bookDao.delete(conn,id);} catch (Exception e) {e.printStackTrace();}// 重定向到FindServletresponse.sendRedirect("FindServlet");}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse* response)*/protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}}4、servlet访问url映射配置:由于客户端是通过URL地址访问web服务器中的资源,所以Servlet程序若想被外界访问,必须把servlet程序映射到⼀个URL地址上,这个⼯作在web.xml⽂件中使⽤<servlet>元素和<servlet-mapping>元素完成,<servlet>元素⽤于注册Servlet,它包含有两个主要的⼦元素:<servlet-name>和<servlet-class>,分别⽤于设置Servlet的注册名称和Servlet的完整类名。

java web笔记

java web笔记

java web笔记JavaWeb是一种基于Java语言开发的Web应用程序开发技术,其主要模块包括Servlet、JSP、JavaBean以及Java EE(Enterprise Edition)等。

1. ServletServlet是一种Java程序,用于处理HTTP请求和响应。

它可以接收来自客户端的HTTP请求并生成HTTP响应。

Servlet实现了javax.servlet.Servlet接口,可以在Web容器中运行。

Servlet可以通过doGet()、doPost()等方法处理HTTP请求,通过request对象获取请求参数,通过response对象生成响应内容。

Servlet还可以通过init()方法进行初始化,通过destroy()方法进行终止。

2. JSPJSP是Java Server Pages的缩写,它是一种基于HTML和Java 的Web开发技术。

JSP可以将Java代码嵌入到HTML页面中,以便动态生成Web页面。

JSP页面可以使用JavaBean来处理业务逻辑,在JSP中使用标签库可以简化开发,如JSTL标签库、EL表达式等。

3. JavaBeanJavaBean是一种Java类,它封装了应用程序中的数据和业务逻辑。

JavaBean通常包含get/set方法,可以通过这些方法访问和修改JavaBean中的属性。

JavaBean的作用是将数据和业务逻辑分离,使得应用程序具有更高的可维护性和可重用性。

4. Java EEJava EE是Java平台的企业版,它提供了一系列API和规范,用于开发大型分布式Web应用程序。

Java EE包含了Servlet、JSP、JavaBean等技术,还提供了EJB(Enterprise Java Bean)、JPA(Java Persistence API)、JMS(Java Message Service)等高级技术。

Java EE还包含了Web容器和应用服务器,如Tomcat、WebLogic、WebSphere等,这些容器可以运行Java Web程序,提供了对Java Web 程序的支持和管理。

Jsp和Servlet关系

Jsp和Servlet关系

Jsp和Servlet关系为什么会出现Jsp?其实对于服务器来说它只认识Servlet,我们完全可以在Servlet⽤resp.getWriter().write("");画出⽹页的界⾯,但是仅仅⼀个很简单的界⾯就要重复的书写resp.getWriter().write(""),并且这还没有加上js、css以及jquery。

但是我们在Servlet写的是java代码可以有逻辑的判断,但是在html、css中⽆法加⼊逻辑导致页⾯是静态的。

为了解决这⼀问题出现了jsp,在jsp中可以书写Java代码、js代码、html代码等。

我们都知道浏览器发送请求到服务器,服务器通过解析其中Servlet的别名找到对应的Servlet并执⾏其中的service⽅法做出处理和响应,那么对于服务器来说它只认识Servlet,那么我们编辑的Jsp到底是如何被服务器识别的?实际上服务器还是将.jsp当作Servlet的别名在你局部配置下的web.xml找有没有对应的Servlet,如果没有找到对应的Servlet就去Tomcat的公共配置下的web.xml(Tomcat安装⽬录conf下的web.xml)找对应的Servlet。

会找到如下内容:org.apache.jasper.servlet.JspServlet将对应的jsp⽂件转为Servlet。

那么转的Servlet在什么地⽅呢?打开Tomcat下的work⽂件夹⼀直点到:找你正在运⾏的项⽬的jsp测试的jsp:<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Insert title here</title></head><body>666</body></html> 被编译好的Java⽂件:/** Generated by the Jasper component of Apache Tomcat* Version: Apache Tomcat/8.5.46* Generated at: 2019-10-16 09:05:10 UTC* Note: The last modified time of this file was set to* the last modified time of the source file after* generation to assist with modification tracking.*/package org.apache.jsp;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.jsp.*;public final class index_jsp extends org.apache.jasper.runtime.HttpJspBaseimplements org.apache.jasper.runtime.JspSourceDependent,org.apache.jasper.runtime.JspSourceImports {private static final javax.servlet.jsp.JspFactory _jspxFactory =javax.servlet.jsp.JspFactory.getDefaultFactory();private static java.util.Map<ng.String,ng.Long> _jspx_dependants;private static final java.util.Set<ng.String> _jspx_imports_packages;private static final java.util.Set<ng.String> _jspx_imports_classes;static {_jspx_imports_packages = new java.util.HashSet<>();_jspx_imports_packages.add("javax.servlet");_jspx_imports_packages.add("javax.servlet.http");_jspx_imports_packages.add("javax.servlet.jsp");_jspx_imports_classes = null;}private volatile javax.el.ExpressionFactory _el_expressionfactory;private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager;public java.util.Map<ng.String,ng.Long> getDependants() {return _jspx_dependants;}public java.util.Set<ng.String> getPackageImports() {return _jspx_imports_packages;}public java.util.Set<ng.String> getClassImports() {return _jspx_imports_classes;}public javax.el.ExpressionFactory _jsp_getExpressionFactory() {if (_el_expressionfactory == null) {synchronized (this) {if (_el_expressionfactory == null) {_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();}}}return _el_expressionfactory;}public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() {if (_jsp_instancemanager == null) {synchronized (this) {if (_jsp_instancemanager == null) {_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());}}}return _jsp_instancemanager;}public void _jspInit() {}public void _jspDestroy() {}public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)throws java.io.IOException, javax.servlet.ServletException {final ng.String _jspx_method = request.getMethod();if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method) && !javax.servlet.DispatcherType.ERROR.equals(request. response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET POST or HEAD");return;}final javax.servlet.jsp.PageContext pageContext;javax.servlet.http.HttpSession session = null;final javax.servlet.ServletContext application;final javax.servlet.ServletConfig config;javax.servlet.jsp.JspWriter out = null;final ng.Object page = this;javax.servlet.jsp.JspWriter _jspx_out = null;javax.servlet.jsp.PageContext _jspx_page_context = null;try {response.setContentType("text/html; charset=ISO-8859-1");pageContext = _jspxFactory.getPageContext(this, request, response,null, true, 8192, true);_jspx_page_context = pageContext;application = pageContext.getServletContext();config = pageContext.getServletConfig();session = pageContext.getSession();out = pageContext.getOut();_jspx_out = out;out.write("\r\n");out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"/TR/html4/loose.dtd\">\r\n");out.write("<html>\r\n");out.write("<head>\r\n");out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">\r\n");out.write("<title>Insert title here</title>\r\n");out.write("</head>\r\n");out.write("<body>\r\n");out.write("666\r\n");out.write("</body>\r\n");out.write("</html>");} catch (ng.Throwable t) {if (!(t instanceof javax.servlet.jsp.SkipPageException)){out = _jspx_out;if (out != null && out.getBufferSize() != 0)try {if (response.isCommitted()) {out.flush();} else {out.clearBuffer();}} catch (java.io.IOException e) {}if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);else throw new ServletException(t);}} finally {_jspxFactory.releasePageContext(_jspx_page_context);}}}但是我们发现这个类并没有继承HttpServlet⽽是继承了org.apache.jasper.runtime.HttpJspBase并且⾥⾯也没有service⽅法⽽是_jspservice⽅法。

servlet技术简介

servlet技术简介

Servlet技术是Sun公司提供的一种实现动态网页的解决方案,它是基于Java编程语言的WEB服务器端编程技术,主要用于在WEB服务器端获得客户端的访问请求信息和动态生成对客户端的响应消息。

Servlet技术也是JSP技术(另外一种动态网页开发技术)的基础。

一个Servlet程序就是一个实现了特殊接口的Java类,用于被支持Servlet的WEB服务器调用和运行,即只能运行于具有Servlet引擎的WEB服务器端。

一个Servlet程序负责处理它所对应的一个或一组URL地址的访问请求,接收访问请求信息和产生响应内容。

Applet是用于浏览器端的Java小程序,在浏览器端被解释执行,用于在HTML网页中实现一些桌面应用程序的功能,被称为“小应用程序”。

Servlet是用于WEB服务器端的Java小程序,它在WEB服务器端被解释执行,用于处理客户端的请求和产生动态网页内容。

源于Applet的命名,这种WEB服务器端的Java小程序就被命名为了Servlet,与Applet相对应,Servlet可以被称之为“小服务程序”。

Servlet与普通java程序相比,只是输入信息的来源和输出结果的目标不一样,所以,普通Java程序所能完成的大多数任务,Servlet程序都可以完成。

Servlet程序具有如下的一些基本功能:l 获取客户端通过HTML的FORM表单递交的数据和URL后面的参数信息;l 创建对客户端的响应消息内容;l 访问服务器端的文件系统;l 连接数据库并开发基于数据库的应用;l 调用其它的Java类。

Servlet是运行在服务器端的多线程纯java程序,它处理请求的信息并将信息发送到客户端。

这样说吧其实你的JSP页面在客户端请求过后会由WEB容器转译成Servlet源代码,再将Servlet源代码经过编译加载到内存中执行,最后把结果响应给客户端。

====================================================================== =========================================servlet简介servlet容器:负责处理客户请求、把请求传送给servlet并把结果返回给客户。

JSP技术介绍

JSP技术介绍
有非常快的响应(这避免了CGI-BIN为每个HTTP请求生
成一个新的进程的问题)。

JSP页面可以包含在多种不同的应用体系结构或 者模型中,可以用于由不同协议、组件和格式所组成 的联合体中。基于JSP的动态信息发布技术是一个开放 的、可扩展的建立动态Web页面的标准。不论采用什 么创建工具,开发人员都可以使用JSP页面来创建可移 植的Web应用,在不同的Web应用服务器上运行。

JSP页面通常被编译成为Java Servlets,这是一个标 准的Java扩展。页面开发人员能够访问全部的Java应用 环境,以利用Java技术的扩展性和可移植性。

当JSP页面第一次被调用时,如果它还不存在,就会
被编译成为一个Java Servlets类,并且存储在服务器的内
存中。这就使得在接下来的对该页面的调用中,服务器会
(3)强大的可伸缩性。从只有一个小的Jar文件就可以运 行Servlet/JSP,到由多台服务器进行集群和负载均衡,到 多台Application进行事务处理,消息处理,一台服务器
到无数台服务器,Java显示了一个巨大的生命力。
(4)多样化和功能强大的开发工具支持。这一点与ASP很
像,Java已经有了许多非常优秀的开发工具,而且许多可

由于JSP页面的内置脚本语言是基于Java的,而 且所有的JSP页面都被编译成为Java Servlets,所以 JSP页面具有Java技术的所有好处,包括健壮的存储 管理和安全性。作为Java平台的一部分,JSP拥有 Java编程语言“一次编写,各处运行”的特点。
JSP的应用模型
利用JSP技术,动态信息由JSP页面来表现,JSP 页面由安装在Web服务器或者使用JSP的应用服务器 上的JSP引擎执行。JSP引擎接受客户端对JSP页面的 请求,并且生成JSP页面作为对客户端的响应。

JSP应用与开发技术第12、13、14章 课后习题答案

JSP应用与开发技术第12、13、14章 课后习题答案

第12章Servlet基础1.简述Servlet和JSP的关系。

答:Servlet是服务器端运行的一种Java应用程序。

当浏览器端有请求则将其结果传递给浏览器。

在JSP中使用到的所有对象都将被转换为Servlet或者非Servlet的Java对象,然后被执行,所以执行JSP实际上与执行Servlet是一样的。

2.简述Servlet的生命周期。

答:Servlet的生命周期可分为下面几个阶段:(1)装载Servlet。

(2)实例化一个Servlet实例对象。

(3)调用Servlet的init( )方法进行初始化。

(4)服务。

(5)卸载。

3.简述HttpSession接口的功能和使用方法。

答:.HttpSession接口是Servlet提供会话追踪解决方案。

HttpSession对象存放在服务器端,只是对cookie和url重写技术的封装应用。

使用HttpSession进行会话控制的过程:(1)获得一个HttpSession实例对象;(2)访问和设置与会话相关联信息,维护会话的状态;(3)废弃会话数据。

4.简述开发一个Servlet所需要的步骤。

答:第一步:编写Servlet实例第二步:在web.xml文件中配置该Servlet第三步:编写其它文件5.编写一个html页面和一个Servelt,实现利用Servelt的doPost方法读取html文件中Form表单内容。

答:参考12.6.26.写一个利用HttpSession接口的用户登录的Servlet,当用户已经登录时,返回欢迎信息;否则转向登录页面。

答:第一步:编写Servlet实例SessionServlet.java所示。

package com;import java.io.*;import java.util.*;import javax.servlet.*;import javax.servlet.http.*;/**** 使用HttpSession管理会话的登录Servlet*/public class LoginServlet extends HttpServlet {p rotected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { doPost(request, response);}p rotected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=GB2312");PrintWriter out = response.getWriter();out.println("<html>");out.println("<body>");out.println("<head>");out.println("<title>使用HttpSession管理会话的登录页面</title>");out.println("</head>");out.println("<body>");// 获取会话对象HttpSession session = request.getSession();// 从会话对象中读取数据Boolean isLogin = (Boolean) session.getAttribute("isLogin");if (isLogin == null) {isLogin = Boolean.FALSE;}String user = request.getParameter("user");String password = request.getParameter("pass");if (isLogin.booleanValue()) {// 从会话对象中读取数据user = (String) session.getAttribute("user");Date loginTime = new Date(session.getCreationTime());out.println("<h2>欢迎您," + user + "!</h2>");out.println("<h2>您的登录时间是:" + loginTime + "!</h2>");} else if ((user != null) && (password != null)) {// 在会话对象中保存数据session.setAttribute("user", user);session.setAttribute("isLogin", Boolean.TRUE);Date loginTime = new Date(session.getCreationTime());out.println("<h2>欢迎您," + user + "!</h2>");out.println("<h2>您的登录时间是:" + loginTime + "!</h2>");} else {out.println("<h2>请在下面输入登录信息</h2>");out.println("<form method=\"post\" action=\"login\">");out.println("<table>");out.println("<tr>");out.println("<td>用户名:</td>");out.println("<td><input name=\"user\" type=\"text\"></td>");out.println("</tr>");out.println("<tr>");out.println("<td>密码:</td>");out.println("<td><input name=\"pass\" type=\"password\"></td>");out.println("</tr>");out.println("<tr>");out.println("<td></td>");out.println("<td><input name=\"ok\" type=\"submit\" value=\"确定\">");out.println("<input name=\"cancel\" type=\"reset\" value=\"重置\"></td>");out.println("</tr>");out.println("</table>");out.println("</form>");}out.println("</body>");out.println("</html>");}}第二步:在web.xml文件中配置该Servlet<web-app>……<!-- ServerInfoServlet definition --><servlet><description></description><display-name>getSession</display-name><servlet-name> getSession </servlet-name><servlet-class>com.SessionServlet</servlet-class></servlet><!-- SessionServlet definition --><servlet-mapping><servlet-name>getSession</servlet-name><url-pattern>/getSession</url-pattern></servlet-mapping>……</web-app>第13章使用Servlet过滤器和监听器1、什么是过滤器?什么是监听器?分别应用在哪些方面?答:对Web应用来说,过滤器就是驻留在服务器端,在源数据和目的数据间,对Web请求和Web响应的头属性(Header)和内容体(Body)进行操作的一种特殊Web组件。

jsp的工作原理是什么意思

jsp的工作原理是什么意思

jsp的工作原理是什么意思
JSP(JavaServer Pages)是一种用于在服务器端生成动态网页
的技术。

其工作原理如下:
1. 客户端请求一个包含JSP标记的网页。

2. 服务器接收到请求后,将JSP文件翻译为Java Servlet。

3. Servlet被编译为Java字节码,并由Java虚拟机执行。

4. 运行时,Servlet生成动态内容并将其插入HTML页面中。

5. 服务器将生成的动态网页发送回客户端,用于显示。

JSP的工作原理主要涉及三个组件:编译器(JSP编译器),
容器(Servlet容器)和Java虚拟机。

编译器将JSP文件翻译
为Java Servlet,并将其编译为可由Java虚拟机执行的字节码。

容器负责管理和执行Servlet,并在运行时生成动态内容。

最终,Java虚拟机将执行生成的Servlet,并将动态生成的网页
发送回客户端。

WEB开发基础之Servlet和JSP幻灯片

WEB开发基础之Servlet和JSP幻灯片
WEB开发基础之Servlet和JSP
交流
目录
Java Web技术概述 Servlet技术介绍 JSP技术介绍 模式介绍
Java网络程序设计的基本概念

网络将世界联系在一起,使世界变得更加丰富多彩。同时网络 互连是一个内容丰富而复杂的主题,所以这方面的程序设计涉 及面很广且不易掌握 与其他语言相比,Java语言在网络应用程序方面具有一定的优 势。
Servlet容器、Web服务器和应用服务器

Servlet容器
也称为Servlet引擎 是一个编译好的可执行程序,它是web服务器与servlet间的的媒介 负责将请求翻译成Servlet能够理解的形式传递给servlet,同时传给servlet一个对象 使之可以送回响应 负责管理servlet的生命周期
JSP是什么?

Байду номын сангаас
JSP(Java Server Page)技术是一个纯Java 平台的技术, 是在Servlet基础上开发的动态Web制作技术。可以将Web 页面中的动态部分和静态的HTML相分离。主要用于对请求 动态生成的相应的HTML回复。
JSP的技术优点

跨平台 搭配可重复使用的组件 采用标签化页面开发 相比Servlet的优点
Servlet接口
• 所有servlets 必须实现这一接口 • Servlet接口的所有方法都是被自动调用 的
Servlet API(续)
HttpServlet类
• 覆盖了javax.servlet.Servlet接口的service方法
• service方法由servlet容器调用,对客户端的请求作出响应。它会根 据请求类型的不同自动调用doGet或doPost等方法

尚学堂JSP&Servlet

尚学堂JSP&Servlet

初始化Servlet的重载 init(ServletConfig config) 里使用
作业
Servlet实例化对象后会调用init()方法,而 init()方法有2种重载的形式,因为这个方法 是被引擎自动调用的,编程测试其优先顺 序
HttpServeltRequest接口
封装浏览器发送的请求的所有内容
示例:页面访问次数
Servlet里的转发与重定向
转发:request.getRequestDispatcher(页 面地址).forward(request,response)
getRequestDispatcher接口执行转发的任务
重定向:response.sendRedirect(页面地 址);
<%@ directive {attribute=“value”}%>
JSP指令元素
指令元素有三种:
page:作用于整个JSP页面,定义许多页面属 性 include:在当前JSP页面中静态包含一个文 件 taglib:运行页面使用用户定制的标签
Servlet的运行过程
Servlet的整个生命周期,init()只调用一 次,对一个Servlet的每次访问请求都会调 用一次service()方法,而方法的两个参 数对象都由引擎重新产生。 Tomcat的Context元素可以添加 reloadable属性,设为true可以自动重新加 载修改后的Servlet而不用重启服务器(注意 :只适用于开发阶段)
Servlet&JSP
内容
Servlet
servlet简介 servlet入门 servlet运行过程
JSP
JSP简介 JSP运行机制 JSP语法

简述 servlet 的概念和技术特点。

简述 servlet 的概念和技术特点。

简述servlet 的概念和技术特点。

解析:
servlet 的概念:Servlet(Server Applet)是Java Servlet的简称,称为小服务程序或服务连接器,用Java编写的服务器端程序,具有独立于平台和协议的特性,主要功能在于交互式地浏览和生成数据,生成动态内容。

Servlet 技术具有如下特点:
1.方便:Servlet 提供了大量的实用工具例程,如处理很难完成的HTML 表
单数据、读取和设置HTTP 头,以及处理Cookie 和跟踪会话等。

2.跨平台:Servlet 使用Java 类编写,可以在不同的操作系统平台和不同的
应用服务器平台运行。

3.灵活性和可扩展性强:采用Servlet 开发的Web 应用程序,由于Java类
的继承性及构造函数等特点,使得应用灵活,可随意扩展。

java中常用英文简写全拼与中文意思

java中常用英文简写全拼与中文意思

API (Application Programming Interface) 应用编程接口JRE (Java Runtime Enviroment) Java 运行时环境JDK (Java Development Kit) Java开发工具包SDK(Software Development Kit, 即软件开发工具包)JVM (Java Virtual Machine) Java虚拟机JNI (Java Native Interface) Java本地接口AWT (Abstract Windows Toolekit) 抽象窗口工具箱JNDI (Java Naming & Directory Interface) JAVA命名目录服务.主要提供的功能是:提供一个目录系统,让其它各地的应用程序在其上面留下自己的索引,从而满足快速查找和定位分布式应用程序的功能。

JMS (Java Message Service)JAVA消息服务.主要实现各个应用程序之间的通讯.包括点对点和广播.JTA (Java Transcation API) JAVA事务服务.提供各种分布式事务服务.应用程序只需调用其提供的接口即可.JAF (Java Action FrameWork) JAVA安全认证框架.提供一些安全控制方面的框架.让开发者通过各种部署和自定义实现自己的个性安全控制策略.RMI (Remote Method Interface) 远程方法调用CVS (Concurrent Versions System) 版本控制器SVN (Subversion) 版本控制器TC (Test Case) 测试用例,是为某个特殊目标而编制的一组测试输入、执行条件以及预期结果,以便测试某个程序路径或核实是否满足某个特定需求。

指对一项特定的软件产品进行测试任务的描述,体现测试方案、方法、技术和策略。

内容包括测试目标、测试环境、输入数据、测试步骤、预期结果、测试脚本等,并形成文档。

servlet通俗易懂的基本介绍

servlet通俗易懂的基本介绍

1、Servlet和JSP概述1.1 Java Servlet及其特点Servlet是Java技术对CGI编程的回答。

Servlet程序在服务器端运行,动态地生成Web页面。

与传统的CGI和许多其他类似CGI的技术相比,Java Servlet具有更高的效率,更容易使用,功能更强大,具有更好的可移植性,更节省投资(更重要的是,Servlet程序员收入要比Perl程序员高:-):⏹高效。

在传统的CGI中,每个请求都要启动一个新的进程,如果CGI程序本身的执行时间较短,启动进程所需要的开销很可能反而超过实际执行时间。

而在Servlet中,每个请求由一个轻量级的Java线程处理(而不是重量级的操作系统进程)。

在传统CGI中,如果有N个并发的对同一CGI程序的请求,则该CGI程序的代码在内存中重复装载了N 次;而对于Servlet,处理请求的是N个线程,只需要一份Servlet类代码。

在性能优化方面,Servlet也比CGI有着更多的选择,比如缓冲以前的计算结果,保持数据库连接的活动,等等。

⏹方便。

Servlet提供了大量的实用工具例程,例如自动地解析和解码HTML表单数据、读取和设置HTTP头、处理Cookie、跟踪会话状态等。

⏹功能强大。

在Servlet中,许多使用传统CGI程序很难完成的任务都可以轻松地完成。

例如,Servlet能够直接和Web服务器交互,而普通的CGI程序不能。

Servlet还能够在各个程序之间共享数据,使得数据库连接池之类的功能很容易实现。

⏹可移植性好。

Servlet用Java编写,Servlet API具有完善的标准。

因此,为I-Planet Enterprise Server写的Servlet无需任何实质上的改动即可移植到Apache、Microsoft IIS或者WebStar。

几乎所有的主流服务器都直接或通过插件支持Servlet。

⏹节省投资。

不仅有许多廉价甚至免费的Web服务器可供个人或小规模网站使用,而且对于现有的服务器,如果它不支持Servlet的话,要加上这部分功能也往往是免费的(或只需要极少的投资)。

JSP语法基础

JSP语法基础

JSP语法基础1、JSP基本概念JSP(Java Server Pages,Java服务器页面)是一种Web动态页面技术,JSP是嵌入了Java程序段的HTML 文件,由HTML元素(静态部分)、JSP元素(动态部分)和JSP注释组成。

JSP文件后缀名为.jsp。

JSP运行时会被容器翻译为Servlet源代码(xxx_jsp.java)、自动编译为.class文件(xxx_jsp.class)、载入.class文件,然后生成Servlet对象。

JSP和Servlet一样是服务器端技术,允许运行在Web服务器端。

JSP定义在JavaWeb工程中WebRoot根路径下或其下的某个目录,其访问方式和访问HTML文件一致。

注意:如果JSP文件放在WEB-INF目录中时,不能直接访问,需通过Servlet转发。

JSP在运行时会动态编译成一个Servlet,其本质上是就是一个Servlet,JSP是对Servlet技术的扩展。

Servlet完全由Java程序代码构成,擅长于流程控制和业务逻辑处理,一般用作控制器(Controller);JSP 由HTML元素和JSP元素构成,对页面的静态内容和动态内容进行了有效分离,擅长于内容的展示,一般用作视图(View)。

注:翻译生成的xxx_jsp.java和xxx_jsp.class文件的位置:Tomcat中,在apache-tomcat\work\Catalina目录需;在Eclipse中,在workspace下\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\XXX\org\apache\jsp。

2、JSP元素JSP元素包括脚本元素、指令元素和动作元素。

脚本元素(3种)用来声明类成员与方法。

使用<%!与%>声明变量时,必须小心数据共享与线程安全的问题。

Servlet和JSP技术简述中英文资料对照外文翻译文献综述

Servlet和JSP技术简述中英文资料对照外文翻译文献综述

Servlet和JSP技术简述中英文资料对照外文翻译文献综述An Overview of Servlet and JSP Technology 1.1 A Servlet's JobServlets are Java programs that run on Web or application servers, acting as a middle layer between requests coming from Web browsers or other HTTP clients and databases or applications on the HTTP server. Their job is to perform the following tasks, as illustrated in Figure 1-1.Figure 1-11.Read the explicit data sent by the client.The end user normally enters this data in an HTML form on a Web page. However, the data could also come from an applet or a custom HTTP client program.2.Read the implicit HTTP request data sent by the browser.Figure 1-1 shows a single arrow going from the client to the Web server (the layer where servlets and JSP execute), but there are really two varieties of data: the explicit data that the end user enters in a form and the behind-the-scenes HTTP information. Both varieties are critical. The HTTP information includes cookies, information about media types and compression schemes the browser understands, and so on. 3.Generate the results.This process may require talking to a database, executing an RMI or EJB call, invoking a Web service, or computing the response directly. Your real data may be ina relational database. Fine. But your database probably doesn't speak HTTP or return results in HTML, so the Web browser can't talk directly to the database. Even if it could, for security reasons, you probably would not want it to. The same argument applies to most other applications. You need the Web middle layer to extract the incoming data from the HTTP stream, talk to the application, and embed the results inside a document.4.Send the explicit data (i.e., the document) to the client.This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), or even a compressed format like gzip that is layered on top of some other underlying format. But, HTML is by far the most common format, so an important servlet/JSP task is to wrap the results inside of HTML.5.Send the implicit HTTP response data.Figure 1-1 shows a single arrow going from the Web middle layer (the servlet or JSP page) to the client. But, there are really two varieties of data sent: the document itself and the behind-the-scenes HTTP information. Again, both varieties are critical to effective development. Sending HTTP response data involves telling the browser or other client what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.1.2 Why Build Web Pages Dynamically?many client requests can be satisfied by prebuilt documents, and the server would handle these requests without invoking servlets. In many cases, however, a static result is not sufficient, and a page needs to be generated for each request. There are a number of reasons why Web pages need to be built on-the-fly:1.The Web page is based on data sent by the client.For instance, the results page from search engines and order-confirmation pages at online stores are specific to particular user requests. You don't know what to display until you read the data that the user submits. Just remember that the user submits two kinds of data: explicit (i.e., HTML form data) and implicit (i.e., HTTP requestheaders). Either kind of input can be used to build the output page. In particular, it is quite common to build a user-specific page based on a cookie value.2.The Web page is derived from data that changes frequently.If the page changes for every request, then you certainly need to build the response at request time. If it changes only periodically, however, you could do it two ways: you could periodically build a new Web page on the server (independently of client requests), or you could wait and only build the page when the user requests it. The right approach depends on the situation, but sometimes it is more convenient to do the latter: wait for the user request. For example, a weather report or news headlines site might build the pages dynamically, perhaps returning a previously built page if that page is still up to date.3.The Web page uses information from corporate databases or other server-side sources.If the information is in a database, you need server-side processing even if the client is using dynamic Web content such as an applet. Imagine using an applet by itself for a search engine site:"Downloading 50 terabyte applet, please wait!" Obviously, that is silly; you need to talk to the database. Going from the client to the Web tier to the database (a three-tier approach) instead of from an applet directly to a database (a two-tier approach) provides increased flexibility and security with little or no performance penalty. After all, the database call is usually the rate-limiting step, so going through the Web server does not slow things down. In fact, a three-tier approach is often faster because the middle tier can perform caching and connection pooling.In principle, servlets are not restricted to Web or application servers that handle HTTP requests but can be used for other types of servers as well. For example, servlets could be embedded in FTP or mail servers to extend their functionality. And, a servlet API for SIP (Session Initiation Protocol) servers was recently standardized (see /en/jsr/detail?id=116). In practice, however, this use of servlets has not caught on, and we'll only be discussing HTTP servlets.1.3 The Advantages of Servlets Over "Traditional" CGIJava servlets are more efficient, easier to use, more powerful, more portable, safer, and cheaper than traditional CGI and many alternative CGI-like technologies. 1.EfficientWith traditional CGI, a new process is started for each HTTP request. If the CGI program itself is relatively short, the overhead of starting the process can dominate the execution time. With servlets, the Java virtual machine stays running and handles each request with a lightweight Java thread, not a heavyweight operating system process. Similarly, in traditional CGI, if there are N requests to the same CGI program, the code for the CGI program is loaded into memory N times. With servlets, however, there would be N threads, but only a single copy of the servlet class would be loaded. This approach reduces server memory requirements and saves time by instantiating fewer objects. Finally, when a CGI program finishes handling a request, the program terminates. This approach makes it difficult to cache computations, keep database connections open, and perform other optimizations that rely on persistent data. Servlets, however, remain in memory even after they complete a response, so it is straightforward to store arbitrarily complex data between client requests. 2.ConvenientServlets have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such high-level utilities. In CGI, you have to do much of this yourself. Besides, if you already know the Java programming language, why learn Perl too? You're already convinced that Java technology makes for more reliable and reusable code than does Visual Basic, VBScript, or C++. Why go back to those languages for server-side programming?3.PowerfulServlets support several capabilities that are difficult or impossible to accomplish with regular CGI. Servlets can talk directly to the Web server, whereas regular CGI programs cannot, at least not without using a server-specific API. Communicatingwith the Web server makes it easier to translate relative URLs into concrete path names, for instance. Multiple servlets can also share data, making it easy to implement database connection pooling and similar resource-sharing optimizations. Servlets can also maintain information from request to request, simplifying techniques like session tracking and caching of previous computations.4.PortableServlets are written in the Java programming language and follow a standard API. Servlets are supported directly or by a plugin on virtually every major Web server. Consequently, servlets written for, say, Macromedia JRun can run virtually unchanged on Apache Tomcat, Microsoft Internet Information Server (with a separate plugin), IBM WebSphere, iPlanet Enterprise Server, Oracle9i AS, or StarNine WebStar. They are part of the Java 2 Platform, Enterprise Edition, so industry support for servlets is becoming even more pervasive.5.InexpensiveA number of free or very inexpensive Web servers are good for development use or deployment of low- or medium-volume Web sites. Thus, with servlets and JSP you can start with a free or inexpensive server and migrate to more expensive servers with high-performance capabilities or advanced administration utilities only after your project meets initial success. This is in contrast to many of the other CGI alternatives, which require a significant initial investment for the purchase of a proprietary package.Price and portability are somewhat connected. For example, Marty tries to keep track of the countries of readers that send him questions by email. India was near the top of the list, probably #2 behind the U.S. Marty also taught one of his JSP and servlet training courses (see /) in Manila, and there was great interest in servlet and JSP technology there.Now, why are India and the Philippines both so interested? We surmise that the answer is twofold. First, both countries have large pools of well-educated software developers. Second, both countries have (or had, at that time) highly unfavorable currency exchange rates against the U.S. dollar. So, buying a special-purpose Webserver from a U.S. company consumed a large part of early project funds.But, with servlets and JSP, they could start with a free server: Apache Tomcat (either standalone, embedded in the regular Apache Web server, or embedded in Microsoft IIS). Once the project starts to become successful, they could move to a server like Caucho Resin that had higher performance and easier administration but that is not free. But none of their servlets or JSP pages have to be rewritten. If their project becomes even larger, they might want to move to a distributed (clustered) environment. No problem: they could move to Macromedia JRun Professional, which supports distributed applications (Web farms). Again, none of their servlets or JSP pages have to be rewritten. If the project becomes quite large and complex, they might want to use Enterprise JavaBeans (EJB) to encapsulate their business logic. So, they might switch to BEA WebLogic or Oracle9i AS. Again, none of their servlets or JSP pages have to be rewritten. Finally, if their project becomes even bigger, they might move it off of their Linux box and onto an IBM mainframe running IBM WebSphere. But once again, none of their servlets or JSP pages have to be rewritten.6.SecureOne of the main sources of vulnerabilities in traditional CGI stems from the fact that the programs are often executed by general-purpose operating system shells. So, the CGI programmer must be careful to filter out characters such as backquotes and semicolons that are treated specially by the shell. Implementing this precaution is harder than one might think, and weaknesses stemming from this problem are constantly being uncovered in widely used CGI libraries.A second source of problems is the fact that some CGI programs are processed by languages that do not automatically check array or string bounds. For example, in C and C++ it is perfectly legal to allocate a 100-element array and then write into the 999th "element," which is really some random part of program memory. So, programmers who forget to perform this check open up their system to deliberate or accidental buffer overflow attacks.Servlets suffer from neither of these problems. Even if a servlet executes a system call (e.g., with Runtime.exec or JNI) to invoke a program on the local operatingsystem, it does not use a shell to do so. And, of course, array bounds checking and other memory protection features are a central part of the Java programming language.7.MainstreamThere are a lot of good technologies out there. But if vendors don't support them and developers don't know how to use them, what good are they? Servlet and JSP technology is supported by servers from Apache, Oracle, IBM, Sybase, BEA, Macromedia, Caucho, Sun/iPlanet, New Atlanta, ATG, Fujitsu, Lutris, Silverstream, the World Wide Web Consortium (W3C), and many others. Several low-cost plugins add support to Microsoft IIS and Zeus as well. They run on Windows, Unix/Linux, MacOS, VMS, and IBM mainframe operating systems. They are the single most popular application of the Java programming language. They are arguably the most popular choice for developing medium to large Web applications. They are used by the airline industry (most United Airlines and Delta Airlines Web sites), e-commerce (), online banking (First USA Bank, Banco Popular de Puerto Rico), Web search engines/portals (), large financial sites (American Century Investments), and hundreds of other sites that you visit every day.Of course, popularity alone is no proof of good technology. Numerous counter-examples abound. But our point is that you are not experimenting with a new and unproven technology when you work with server-side Java.Servlet和JSP技术简述1.1 Servlet的功能Servlets是运行在Web或应用服务器上的Java程序,它是一个中间层,负责连接来自Web浏览器或其他HTTP客户程序的请求和HTTP服务器上的数据库或应用程序。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

An Overview of Servlet and JSP TechnologyGildas Avoine and Philippe OechslinEPFL, Lausanne, Switzerland1.1 A Servlet's JobServlets are Java programs that run on Web or application servers, acting as a middle layer between requests coming from Web browsers or other HTTP clients and databases or applications on the HTTP server. Their job is to perform the following tasks, as illustrated in Figure 1-1.Figure 1-11.Read the explicit data sent by the client.The end user normally enters this data in an HTML form on a Web page. However, the data could also come from an applet or a custom HTTP client program.2.Read the implicit HTTP request data sent by the browser.Figure 1-1 shows a single arrow going from the client to the Web server (the layer where servlets and JSP execute), but there are really two varieties of data: the explicit data that the end user enters in a form and the behind-the-scenes HTTP information. Both varieties are critical. The HTTP information includes cookies, information about media types and compression schemes the browser understands, and so on. 3.Generate the results.This process may require talking to a database, executing an RMI or EJB call, invoking a Web service, or computing the response directly. Your real data may be in a relational database. Fine. But your database probably doesn't speak HTTP or return results in HTML, so the Web browser can't talk directly to the database. Even if it could, for security reasons, you probably would not want it to. The same argumentapplies to most other applications. You need the Web middle layer to extract the incoming data from the HTTP stream, talk to the application, and embed the results inside a document.4.Send the explicit data (i.e., the document) to the client.This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), or even a compressed format like gzip that is layered on top of some other underlying format. But, HTML is by far the most common format, so an important servlet/JSP task is to wrap the results inside of HTML.5.Send the implicit HTTP response data.Figure 1-1 shows a single arrow going from the Web middle layer (the servlet or JSP page) to the client. But, there are really two varieties of data sent: the document itself and the behind-the-scenes HTTP information. Again, both varieties are critical to effective development. Sending HTTP response data involves telling the browser or other client what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.1.2 Why Build Web Pages Dynamically?many client requests can be satisfied by prebuilt documents, and the server would handle these requests without invoking servlets. In many cases, however, a static result is not sufficient, and a page needs to be generated for each request. There are a number of reasons why Web pages need to be built on-the-fly:1.The Web page is based on data sent by the client.For instance, the results page from search engines and order-confirmation pages at online stores are specific to particular user requests. You don't know what to display until you read the data that the user submits. Just remember that the user submits two kinds of data: explicit (i.e., HTML form data) and implicit (i.e., HTTP request headers). Either kind of input can be used to build the output page. In particular, it is quite common to build a user-specific page based on a cookie value.2.The Web page is derived from data that changes frequently.If the page changes for every request, then you certainly need to build the response at request time. If it changes only periodically, however, you could do it two ways: you could periodically build a new Web page on the server (independently of client requests), or you could wait and only build the page when the user requests it. The right approach depends on the situation, but sometimes it is more convenient to do the latter: wait for the user request. For example, a weather report or news headlines site might build the pages dynamically, perhaps returning a previously built page if that page is still up to date.3.The Web page uses information from corporate databases or other server-side sources.If the information is in a database, you need server-side processing even if the client is using dynamic Web content such as an applet. Imagine using an applet by itself for a search engine site:"Downloading 50 terabyte applet, please wait!" Obviously, that is silly; you need to talk to the database. Going from the client to the Web tier to the database (a three-tier approach) instead of from an applet directly to a database (a two-tier approach) provides increased flexibility and security with little or no performance penalty. After all, the database call is usually the rate-limiting step, so going through the Web server does not slow things down. In fact, a three-tier approach is often faster because the middle tier can perform caching and connection pooling.In principle, servlets are not restricted to Web or application servers that handle HTTP requests but can be used for other types of servers as well. For example, servlets could be embedded in FTP or mail servers to extend their functionality. And, a servlet API for SIP (Session Initiation Protocol) servers was recently standardized (see /en/jsr/detail?id=116). In practice, however, this use of servlets has not caught on, and we'll only be discussing HTTP servlets.1.3 The Advantages of Servlets Over "Traditional" CGIJava servlets are more efficient, easier to use, more powerful, more portable, safer,and cheaper than traditional CGI and many alternative CGI-like technologies. 1.EfficientWith traditional CGI, a new process is started for each HTTP request. If the CGI program itself is relatively short, the overhead of starting the process can dominate the execution time. With servlets, the Java virtual machine stays running and handles each request with a lightweight Java thread, not a heavyweight operating system process. Similarly, in traditional CGI, if there are N requests to the same CGI program, the code for the CGI program is loaded into memory N times. With servlets, however, there would be N threads, but only a single copy of the servlet class would be loaded. This approach reduces server memory requirements and saves time by instantiating fewer objects. Finally, when a CGI program finishes handling a request, the program terminates. This approach makes it difficult to cache computations, keep database connections open, and perform other optimizations that rely on persistent data. Servlets, however, remain in memory even after they complete a response, so it is straightforward to store arbitrarily complex data between client requests. 2.ConvenientServlets have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such high-level utilities. In CGI, you have to do much of this yourself. Besides, if you already know the Java programming language, why learn Perl too? You're already convinced that Java technology makes for more reliable and reusable code than does Visual Basic, VBScript, or C++. Why go back to those languages for server-side programming?3.PowerfulServlets support several capabilities that are difficult or impossible to accomplish with regular CGI. Servlets can talk directly to the Web server, whereas regular CGI programs cannot, at least not without using a server-specific API. Communicating with the Web server makes it easier to translate relative URLs into concrete path names, for instance. Multiple servlets can also share data, making it easy to implement database connection pooling and similar resource-sharing optimizations.Servlets can also maintain information from request to request, simplifying techniques like session tracking and caching of previous computations.4.PortableServlets are written in the Java programming language and follow a standard API. Servlets are supported directly or by a plugin on virtually every major Web server. Consequently, servlets written for, say, Macromedia JRun can run virtually unchanged on Apache Tomcat, Microsoft Internet Information Server (with a separate plugin), IBM WebSphere, iPlanet Enterprise Server, Oracle9i AS, or StarNine WebStar. They are part of the Java 2 Platform, Enterprise Edition (J2EE; see /j2ee/), so industry support for servlets is becoming even more pervasive.5.InexpensiveA number of free or very inexpensive Web servers are good for development use or deployment of low- or medium-volume Web sites. Thus, with servlets and JSP you can start with a free or inexpensive server and migrate to more expensive servers with high-performance capabilities or advanced administration utilities only after your project meets initial success. This is in contrast to many of the other CGI alternatives, which require a significant initial investment for the purchase of a proprietary package.Price and portability are somewhat connected. For example, Marty tries to keep track of the countries of readers that send him questions by email. India was near the top of the list, probably #2 behind the U.S. Marty also taught one of his JSP and servlet training courses (see /) in Manila, and there was great interest in servlet and JSP technology there.Now, why are India and the Philippines both so interested? We surmise that the answer is twofold. First, both countries have large pools of well-educated software developers. Second, both countries have (or had, at that time) highly unfavorable currency exchange rates against the U.S. dollar. So, buying a special-purpose Web server from a U.S. company consumed a large part of early project funds.But, with servlets and JSP, they could start with a free server: Apache Tomcat(either standalone, embedded in the regular Apache Web server, or embedded in Microsoft IIS). Once the project starts to become successful, they could move to a server like Caucho Resin that had higher performance and easier administration but that is not free. But none of their servlets or JSP pages have to be rewritten. If their project becomes even larger, they might want to move to a distributed (clustered) environment. No problem: they could move to Macromedia JRun Professional, which supports distributed applications (Web farms). Again, none of their servlets or JSP pages have to be rewritten. If the project becomes quite large and complex, they might want to use Enterprise JavaBeans (EJB) to encapsulate their business logic. So, they might switch to BEA WebLogic or Oracle9i AS. Again, none of their servlets or JSP pages have to be rewritten. Finally, if their project becomes even bigger, they might move it off of their Linux box and onto an IBM mainframe running IBM WebSphere. But once again, none of their servlets or JSP pages have to be rewritten.6.SecureOne of the main sources of vulnerabilities in traditional CGI stems from the fact that the programs are often executed by general-purpose operating system shells. So, the CGI programmer must be careful to filter out characters such as backquotes and semicolons that are treated specially by the shell. Implementing this precaution is harder than one might think, and weaknesses stemming from this problem are constantly being uncovered in widely used CGI libraries.A second source of problems is the fact that some CGI programs are processed by languages that do not automatically check array or string bounds. For example, in C and C++ it is perfectly legal to allocate a 100-element array and then write into the 999th "element," which is really some random part of program memory. So, programmers who forget to perform this check open up their system to deliberate or accidental buffer overflow attacks.Servlets suffer from neither of these problems. Even if a servlet executes a system call (e.g., with Runtime.exec or JNI) to invoke a program on the local operating system, it does not use a shell to do so. And, of course, array bounds checking and other memory protection features are a central part of the Java programminglanguage.7.MainstreamThere are a lot of good technologies out there. But if vendors don't support them and developers don't know how to use them, what good are they? Servlet and JSP technology is supported by servers from Apache, Oracle, IBM, Sybase, BEA, Macromedia, Caucho, Sun/iPlanet, New Atlanta, ATG, Fujitsu, Lutris, Silverstream, the World Wide Web Consortium (W3C), and many others. Several low-cost plugins add support to Microsoft IIS and Zeus as well. They run on Windows, Unix/Linux, MacOS, VMS, and IBM mainframe operating systems. They are the single most popular application of the Java programming language. They are arguably the most popular choice for developing medium to large Web applications. They are used by the airline industry (most United Airlines and Delta Airlines Web sites), e-commerce (), online banking (First USA Bank, Banco Popular de Puerto Rico), Web search engines/portals (), large financial sites (American Century Investments), and hundreds of other sites that you visit every day.Of course, popularity alone is no proof of good technology. Numerous counter-examples abound. But our point is that you are not experimenting with a new and unproven technology when you work with server-side Java.Servlet和JSP技术简述Gildas Avoine and Philippe OechslinEPFL, Lausanne, Switzerland1.1 Servlet的功能Servlets是运行在Web或应用服务器上的Java程序,它是一个中间层,负责连接来自Web浏览器或其他HTTP客户程序的请求和HTTP服务器上的数据库或应用程序。

相关文档
最新文档