Chapter 2 Preliminary Knowledge 2.1 Java Program Design Basics J a V is the basis of J S P, to learn J S P technology, J a v A foundation is essential. This section will briefly describe the basic syntax and concepts of J a V a. It is already an reader of J a V A programmer without reading, here is a quick entry for readers who do not have much J a V A experience. Here, the introduction of J ava language is just a basic overview. To learn from JSP, you must have a deep understanding of J ava language. The author recommends the "J Ava Programming Thought" book published by the Machinery Industry Press, this book Limited to the space, there are not many talks. 2.1.1 Java Language Rules J A V A Language Basic Structure Like C / C , anyone who uses process language to prepare a process language can understand most of the structure of the J a V A language. 1. Source code code for program structure J a V A is composed of one or more compilation units (C O m P i L A T I O N n i t), each of which can only contain the following content (except for space and annotation): • Package Statement. • Inlet statements (Import Statements). • Class Declarations. • Interface Declarations. The compiler of each J a V A can contain multiple classes or interfaces, but each compile unit can only have a class or interface being public. After the Java source code is compiled, the J a V A byte code is generated. The byte code of J a V A is composed of a series of instructions that do not depend on the machine, which can be effectively interpreted by the Runtime System of J a V A. J a v a running system works like a virtual machine. In the current J a V A implementation, each compiler is a file that is a suffix. Each compile unit has several classes, after compiling, each class generates one. C L A S s file. The C L A S s file is a code that the J a V A virtual machine can recognize. After introducing J a R concept, you can now compress a number of J a V A files into a J a R file. The new version of J a V A can be used directly to read J A R files. 2. Note Note There are three types: / / Note One-line / * One-line or multi-line comment * // * * Document Note ** / Document comment before placing a variable or function definition, indicating in any automatic generation document system To extract the tools that generate a document, the tool is called Javadoc, which also includes some variables starting with @, such as: @ see, @ version, @ param, etc. For specific usage, see the Tool documentation of JDK. 3. Identifier variables, functions, classes, and objects are identifiers, and programmers need to identify and use things that require identifiers. In the J a V language, the identifier is starting with character _ or $, and the number can be included, the identifier is different, there is no length limit. Effective identifiers such as GoGo Brood_war Hello_And_You $ BILL. Declarations such as int a_number; char _ONECHAR; FLOAT $ BILL.
The following is the J ava keywords: abstractcontinuefor new switchb ooleandefaultgotonull synchronizedb reakdoifpackage thisb ytedoubleimplementspr ivate threadsafeb yvalueelseimportprote cted throwc aseextendsinstanceofp ublic transientc atchfalseintreturn truechar finalinterface short tryc lassfinallylongstatic voidc onstfloatnativesuper while the following words are reserved for use: cast, future, generic, inner, operator, outer , REST, VAR. 4. Data type J a V A uses five basic types: I n t e g e R (integer), F L O a T I N g (floating point number), P O i n (pointer), BO O L E A N (Boolean variable), Character or String (character or string). In addition, there are some composite data types, such as arrays. Integer includes the following types: Integer length (B ITS) Data Type Indications 8 BYT E1 6 Short3 2 INT6 4 LON GFLOATION The data given below the floating point number: 3. 1 4 1 5 9, 3. 1 2 3 E 1 5, 4 E 5 Floating point number length (BITS) Data type indication 3 2 FLOA T6 4 DoubleBoolean Two possible values of the Boolean variable: True FalseCharacter is the example of the character: Chapter 2 Preparatory knowledge 17
Examples given by ASD FString: "Gogo, Rock and Roll" "JSP Advanced Programming" array can define arbitrary types of arrays, such as Char S [], this is a character array; int Array [], This is an integer array; you can also define an array of arrays. INTBLOCK [] [] = new int [2] [3]; array boundaries are detected at runtime to avoid stack overflow. In J a V A, the array is actually an object, and the array has a member variable: L e n g t h. You can use this member function to see the length of any array. Create an array in J a V A, you can use two basic methods: 1) Create an empty array. INT list [] = new int [50]; 2) Fill in the initial value. String names [] = {"chenji", "yuan", "chun", "yang"}; it is equivalent to the following features: String names []; Names = new string [4]; names [0] = new string ("chenji"); names [1] = new string ("yuan"); names [2] = new string ("chun"); Names [3] = New String ("yang"); INT NAME [50]; INT Name [50]; / / will not use new operation to fill an array of unfained sizes. Such as: int name []; for (int i = 0; i <9; i ) {name [i] = i;} 5. There are many developments in the expression J ava language from C language. So the J ava expression and the C language are very similar. Operator operator (Operator) Priority From high to low alignment as follows:. [] () -! ~ Instanceof * /% - << >> >>> <> <=> / ==! = & ^&& ||?: = OP =, (2) When the integer operator is operated, if the operand is the LONG type, the calculation result is the long type, otherwise it will never be byte, short or char. type. Thus, if the variable I is declared as S H O R T or B Y T E, the result of i 1 is I N t. If the result exceeds the value range of this type, the maximum value is made according to this type. Single-scale integer operators are: operator operation - non-~ bit complement plus 1- - minus 118 first part JSP entry
Operator is used to indicate direct plus 1 operation. Incremental operations can also be done indirectly with the plus operator and assignment operation. LVALUE (left value represents Lvalue = 1, Lvalue also means lvalue = lvalue 1 (as long as LVALUE has no side effects). - - operator is used to indicate minus 1 operation. and - - operator can be used as The prefix operator can also be used as a suffix operator. Bottom integer operators are: operator operation plus - reduction * multiplication / in addition to% moderate & bit and | bit or ^ bit or
MyClass AnotherMyObject = (myclass) myObject; ...} is determined if M Y O B J E C T is an example of M Y C L A S S or an example of its subclass. (7) Force and convert J a v a language and interpreter limitations use forced and converted to prevent errors from causing system crash. Integral and floating point numbers can come back and forth back and forth, but integers cannot be forced to convert into an array or object. Objects cannot be enforced as basic types. 6. Java flow control The following control structure is drawn from the C language. (1) Branch structure IF / ELSE branch structure: IF (boolean) {stateManeTs;} else {statements;} Switch branch structure: switch (expr1) {copy expr2: statements; break; case expr3: statements; breaf; default: statements Break;} (2) Cycle structure for loop structure: for (init expr1; test expr2; increment expr3) {statements;} w hile loop structure: while (boolean) {statements;} D O cycle structure: dostatements;} while (Boolean); 20 Part 1 JSP Getting Started
2.1.2 Java variables and functions J a v a include variables and functions. The data variable can be the original type, such as I n t, c h a r, etc. The member function is an executable process. For example, the following program: public class testclasspublic testclass () {i = 10;} public void addi (int J) {i = i j;}} TE ST C LASS contains a variable I and two member functions, TestClass INT first) and addi (int J). The member function is a subroutine that can be called by other classes or ourselves. A special member function called constructor, this function name is generally the same as this class name. It has no return value. When a class is defined in J a V A, one or more optional constructor can be defined, and when an object of this class is created, the object is initialized with a certain constructor. With the previous program example, all member functions and variables are created when the TE S T C L A S c class creates a new instance (creation instance). The constructor is called. TestClass TestObject; TestObject = New TestClass (); Keyword NEW Used to create an instance of a class, a class does not take up memory before initialization, it is just a type definition, when the Test O Bject object is initialized, Test O Bject object The I variable is equal to 1 0. Variable I can be referenced by the object name. (Sometimes called instance variable) TestObject.i ; // TestObject instance variable plus 1, because Test O Bject has all variables and member functions of the TE St C LASS class, you can use the same syntax to call member functions Add i: addi ( 10); Now Test O Bject. I variable is equal to 2 1. J ava does not support the destructor (definition in C ), because the Java object is useless, there is an automatic clearance function, and it also provides a member function of an automatic trash can, called when the object is cleared: protected Void finalize ();} 2.1.3 Sub-class class is a mechanism for creating a new object using the existing object, for example, if there is an H Orse class, you can create a z ebra subclass, z ebra is One of H ORSE. Class Zebra Extends Horse {int number_of_stripes:} Keywords e x t e n d s To define subclasses of the object. Z E B R is the subclass of H O R s E. All features in the H O R s E class will be copied to the z E B R C class, while the Z e B R c class can define your own member functions and instance variables. Z E B R A is called the derived or inheritance of H O R S E. In addition, you may want to override the member function of the base class, and you can use TE S T C L A s S to explain that the following is an example of a generation of a D D i function. Import TestClass; Public Class Newclass Extends TestClass {Chapter 2 Preparatory Knowledge 21
Public Void Addi (INT J);}}} When the instance of the N e W C L A S class is created, the variable I initialization value is 1 0, but the call A D D i produces different results. Newcoject NewObject; newobject = new newclass (); newobject.addi (10); When a new class is created, the access level of the variable and the member function can be launched. Public public void AnyonECANAccess () {} public instance variable and member function can be called by any other class. Protected protected void onlysubclasses () {} protected instance variable and member functions can only be called by their subclasses. Private Private String CreditCardNumber; Private instance variable and member function can only be called in this class. Friendly void mypackageMethod () {} is default, if no access control, instance variables, or function defaults to Friendly, which means accessible by any object in this package, but other ports in other packages are not accessible . For static member functions and variables, sometimes you create a class, I hope that all instances of this class use all variables. That is to say, all of this class object has only the same copy of the instance variable. The keywords of this method are S t a t i c, for example: Class Block {static int number = 50;} All N u m b e R variables from the object created from the B L O C K class are the same. No value of N u m b E r is changed in which object is changed, and the N u m b E r of all objects will change. Again, you can define the S t a t i c member function, but this member function cannot access non-S t a t i c function and variables. Class block {static int number = 50; int localvalue; static void add_local () {localValue ; file: // No run} static void add_static () {Number ; // Run}} 2.1.4 and Super Access a class When instance variables, the THIS keyword is a pointer to this class itself. In the previous TE St C Lass example, the constructor can be added as follows: Public class testclass {22 first part JSP Getting Started
INT i; public testclass () {i = 10;} public testclass (int value) {this.i = value;} public void addi (int J) {i = i j;}} This point points to TE ST C Pointer of the LASS class. If a member function of the parent class is covered in a subclass, you want to call the members of the parent class, you can use the Super key to point to the member function of the parent class. Import testClass; public class newclass extends testclass {public void addi (int J) {i = i (j); super.addi (j);}} The I variable is set to 1 0, then It is 1 5, and finally is set to 2 5 by the parent class (TE ST C LASS). NewcoBject = new newclass (); newobject.addi (10); 2.1.5 Type of To, only one P U b L i c keyword in front of the class, in fact it has four options: A b S T R a c t. An A B S T R A CT class must have at least one virtual function, and an A b S t R A CT class cannot create an object directly, and the object must be created after the subclass can be created. f i n a l A f i n a L declares the end of the subclass chain, and the classes declared by F I n a L can no longer send the child class. P U B L i c. P U B L i C class can be accessed by other classes. In other packages, if you want to use this class, you must first i m P O R t, otherwise it can only be used in the P a C K A g e it defines. S Y N c H R O N I C A B L E. This class identifier means that all members of all classes are synchronized. 2.1.6 A biggest advantage of abstract class-oriented objects is to define how to use this class without having to really define a member function. This is useful when the program is implemented by different users, which does not require the user to use the same member function name. In Java, an example of an Abstract class in the G Raphics class is as follows: Public Abstract Class Graphics {Public Abstract Void Drawline (int x1, int y1, int x2, int y2); public abstract void Drawoval (int x, int y, int y, int Width, int.com); Chapter 2 Preparatory knowledge 23
Public Abstract Void DrawRect (int X, int y, int width);} Several member functions are declared in G R a P H i C S, but the actual code of the member function is achieved in another place. Public class myclass extends graphics {public void Drawline (int x1, int y1, int x2, int y2) {
Package PackageName; If the compilation unit does not have a P A c k A g E statement, the unit is placed in a default unknap packet. In J a V A language, a packet provides a mechanism that can be defined and implemented in another package. Type I m P O R t keywords to indicate classes from other packages. A compiler can automatically enter the specified class and interface into its own package. There are two ways to define the classes and interfaces in other packages: given the names of their packages in front of each reference class and interface: file: // Prefix Package method ACME. Project .Foobarobj = new acme. Project. Foobar (); use the import statement to introduce a class or one interface, or contain their packages. The introduced class and the name of the interface available in the current namespace. When a package is introduced, all public class and interfaces of the package are available. The form is as follows: // introduces all kinds of IMPORT ACME.PROJECT. *; This statement represents A c m e. All public classes in P R O J E C T are introduced into the current package. The following statement enters a class E M P L O Y E C_L I S. File: // introduce Employee_Listimport Acme.Project.emPloyee_List; Employee_List Obj = new Employee_List (); Employee_List (); When using an external class or interface, you must declare the package where the class or interface is required, otherwise the compilation error will be generated. . I M P O R T (introduced) Class Pack (Class Package) Tunes to specify P a c k A g e name such as path and class name, with * matching characters can be transferred with a * matching man. Import java.date; import java.awt. *; If the J a V A source file does not include P A c k a g e, it is placed in the default unnamed P a C K a g e. This is the same as the source file, the class can be introduced: Import myclass; J a v A system package: J A V A language provides a package that contains window toolboxes, utilities, general I / O, tools, and network functions. The usage and class detailed explanation of each package has a detailed description in the document comes with the JDK. I hope the reader can take a look. It is familiar with most commonly used packages to better master the J ava. technology. After understanding the Overview of the J a V A language, you will see three J a V A technology closely related to J S P technology: J a V A E E E A N s, J D b C, Java servlet. 2.2 What is JavaBeansj a v a b e a n s? J a V A B E A S N is a special class, which must comply with the J a V A B E A N S specification. J a V A B E A N S is designed to be visualized in a visual integrated development environment, modularly using component technology to develop applications. However, in J S P, there is no need to use any visualized aspects, but still need to utilize the properties, events, persistence, and userization of J a V A B E A N s to implement modular functions. The attributes, events, persistence, and userization of J a V A B e a N s are described below. Chapter 2 Preparatory Knowledge 25
2.2.1 Properties of JavaBeans J Ava B EANS Properties The properties referred to in the general J ava program, or the properties of objects in all object-oriented programming languages are a concept, and the specific embodiment in the program is class Variables. In J a V A B e a N s design, according to the different effects of the attribute, it is divided into four categories: Simple, INDEX, Bound and C O N s T R a I n e D attribute. 1. SIMPLE Attribute Simple Attribute Indicates that the variable of a pair of G e T / S E T method (C language process or function is called "method" in the J a V A program). The attribute name corresponds to the g e t / s e t method name associated with this property. For example, if there is S e t x and g e t x methods, it is impressed with an attribute called "X". If there is a method name I s x, it is usually implying that "X" is a Boolean property (ie the value of X is T R u e or F A L s E). For example, in this program: public class aldenn1 extends canvas {string ourstring = "hello"; file: // The type is ourstring, type is string public aldenen1 () {file: // Alden1 () is Alden1 constructor Function, the meaning of constructor in C is the same setBackground; setForeground (color.blue);} / * "set" attribute * / public void setstring (String newstring) {ourstring = newstring;} / * "get "Property * / public string getString () {return ourstring;}} 2. Indexed property I ndexed property represents an array value. The value in the array can be obtained using the S e t / g e t method corresponding to this property. This property can also set or achieve the value of the entire array. For example: public class aldenen2 extends canvas {int [] dataset = {1, 2, 3, 4, 5, 6}; // DataSet is an indexed property public aldenen2 () {setBackground (Color.red); setForeground (Color. Blue);} / * Set the entire array * / public void setDataSet (int [] x) {dataset = x;} / * Set a single element value in the array * / public void setDataSet (int index, int x) {dataset [ Index] = x; 26 Part 1 JSP Getting Started
} / * Acquire the entire array value * / public int [] getDataSet () {return dataset;} / * acquired the specified element value * / public int getDataSet (INT X) {Return Dataset [x];}} 3. The bound property B OUND property is to refer to the other object when the value of the property changes. This property triggers a P R O P E R T Y C H A N g E event when each property value changes, and an event is also an object in the J A V A program. The attribute name, the original value of the attribute, and the new value of the attribute change are encapsulated. This event is passed to other B E A N s, as for what actions should be made by the B E A N S of the event, which is defined by itself. When the B A c k g R O U N D attribute of P U S H B U T T O N is binds to the B A C k G R O U N D attribute of D i a L O G, if the B A C k G R O U N D attribute of P U S H B U T T t O N, the B A C Kr R O U N D attribute of D i a L O G also occurs the same. For example: public class alden3 extends Canvas {String ourString = "Hello"; file: // ourString bound property is a private PropertyChangeSupport changes = new PropertyChangeSupport (this); / * Java is a pure object-oriented language, if you want to use some method It must be indicated by the method of which object to use, and the method of the ignition event is performed in the following program, which is used in the PropertyChangeSupport class. So the above declaration and instantiate a Changes object, and will use the Changes's FirePropertyChange method to ignit the property change event. * / Public void setString (string newString) {String oldString = ourString; ourString = newString; / * ourString attribute value has changed, then followed by firing property change event * / changes.firePropertyChange ( "ourString", oldString, newString); } public string getString () {return ourstring;} / ** The following code is used for development tools. We can't predict that Alden3 will become an application in combination with which other Beans, can't predict which other components are related to this change when Alden3 is changed, so Alden3 beans want to reserve some interfaces to development tools. Tools use these interfaces to mount other JavaBeans objects with Alden3. * / Public void addPropertyChangeListener (PropertyChangeLisener l) {changes.addPropertyChangeListener (l);} public void removePropertyChangeListener (PropertyChangeListener l) {changes.removePropertyChangeListener (l);} Chapter 27 Preliminaries
Through the above code, the development tool calls Changes Add P ROPERTY C HANGE L Istener method to register another J ava b Ean into the listener queue L of the Our S TRING property, L is a VE CTOR array that stores any J ava object . The development tool can also use the R E M O V E P R O P E M Ot of C H A N G E S, and the specified object is logged out from the L, the change in the O U R S T R I N g attribute of the A L D e N 3 is no longer related to this object. Of course, when the programmer is handwritten, these two methods can also be called directly to hill other J a V A objects with A L D e n3. 4. CONSTRAINED Property J a V A B E A N S CO N S R A I N e D attribute is that when the value of this attribute changes, other J a V A objects that have been established to reel with this attribute values of some connection. The listener of the CO N S T R A I N e D attribute will prevent the value of the attribute value by throwing the P R O P E R T Y VE TO E X C E P T I O N. For example, the CO N S T R A I n e D attribute in the following program is P R I c e i n c e n t s. public class JellyBean extends Canvas {private PropertyChangeSupport changes = new PropertyChangeSupport (this); private VetoableChangeSupport Vetos = new VetoableChangeSupport (this); / * aforementioned changes the same manner as in Example Vetos VetoableChangeSupport object may be used, to prevent the specific conditions down PriceInCents Value changes. * / ...... Public void setPriceinCents (int newpriceinities) throws propertyvetoException {/ * Method name The role of THROWS PropertyveToException is to throw exceptions when there are other Java objects veto PriceNCents change. * // * to save the original property value * / int oldPriceInCents = ourPriceInCents; / ** ignition properties change veto event * / vetos.fireVetoableChange ( "priceInCents", new Integer (OldPriceInCents), new Integer (newPriceInCents)); / * * If there is any other object veget change, the program throws the exception, no longer continues to perform the following two statements, the method ends.
Unless otherwise rejected objects priceInCents change, then the following code ourPriceIncents assign a new value, and the ignition property change event * / ourPriceInCents = newPriceInCents; changes.firePropertyChange ( "priceInCents", new Integer (oldPriceInCents), new Integer (newPriceInCents ));} / ** The same as the aforementioned CHANGES, also to reserve the interface for the PriceIncents property, so that other objects can be registered into the PriceINCents veto listener queue, or log out of the public void addvetoablechangelistener (VetoAblechangelistener L) {Vetos .addvetoableChangelistener (L); Public Void RemoveveToableChangeListener (VetOableChangeListener L) {vetos.removeveToableChangeListener (L);} ...} From the above example, a CO nstrained property has two listeners: attribute A listener that changes the listener and the reed attribute change. The listener of the veto attribute changes to the corresponding control statement in its object code, and determines whether or not this property value should be rejected in the control statement when monitoring the CO N S T R A I N e D attribute. 28 Part 1 JSP Getting Started
In summary, whether the CO N S T R A I n e D attribute value of a B e a N S may change depending on the other B E A N S or whether the J a V A object allows such changes. The allowable condition is defined in its own class by other B E A N s or J a V A objects. 2.2.2 Event Event Processing of JavaBeans is one of the cores of the J a V A B E A N S architecture. Through the event handling mechanism, some components can be made as an event source, and an event that can be described can be described or other components can be issued. Thus, different components can be combined in the construction tool, and the components communicate between the components, constitute an application. Conceptually, an event is a transfer mechanism that changes in some state between "source object" and "listener objects". There are many different purposes, such as mouse events, window boundary changes events, keyboard events, etc. in Wi N D O W S systems. A general, expandable event mechanism is defined in J a V A and J a V A B e a N s, which provides a public framework for the definition and expansion of the event type and delivery model, and is suitable for a wide range of applications. • High integration with J a V A language and environment. • Events can be described as environmental capture and trigger. • Can make other construction tools to direct contact between events, event sources, and event listeners when designing. • The event mechanism itself does not rely on complex development tools. In particular, it should also be: • An event that can be generated by the specified object class can be found. • Ability to find that the specified object class can observe the events (listening). • Provide a registered mechanism that allows the relationship between the dynamic manipulation of the event source and the event listener. • You don't need other virtual machines and languages. • Efficient event delivery between event sources and listeners. • Enable the neutral mapping of the J a V A B E A N event model and the associated other component architecture event model. 1. Overview The main configuration of the overall structure of the J a V A B E A N S event model: Event source from the event source to the listener is done by calling the J a V A method of the target listener object. A clear J a V A method is defined accordingly for each explicit event. Both of these methods define in the event listener (E V E N T L I S t e n e r) interface, this interface should inherit J V a. U t i l. E V e n T L I S t e n e r. A class that implements some or all of the methods in an event listener interface is an event listener. With the occurrence of the event, the corresponding state is usually encapsulated in the event status object, which must inherit from J a V a. U t i l. E V e n T O B J E C T. Event status objects are transmitted to the listener method that should respond to the event as a single ginseng. The identity of the event source that issues a certain particular event is that the design format of the specified design is the registration method for event listeners and accepts references to the specified event listener interface instance. Sometimes, event monitors cannot directly implement an event listener interface, or other additional actions, an instance of an event adapter class is to be inserted between one source and other one or more listeners to establish them Contact. 2. The status information related to the event status object is generally packaged in an event status object, which is the subclass of J V a. U t i l. E V E N T O B J E C T. According to the design habits, this event status object class name should end with E V e n t. For example: public class mousemovededexampleEvent extends java.util.eventObject {Chapter 2 Preparation Knowledge 29
Protected int x, y; / * Create a mouse mobile event MouseMoveDexampleEvent * / mousemovedexampleEvent (java.awt.component source, point location) {super (Source); x = location.x; y = location.y;} / * get Mouse location * / public point getLocation () {Return New Point (x, y);}} 3. Event listener interface and event listener requires a definition and organizing event manipulation because the J ava event model is based on method calls. Method method. JAVA B EANS, the event manipulation method is defined in inheriting the Java. Util. E VENT L Istener interface, prescribed, the naming of the E VENT L Istener interface is L Istener ends. Any class If you want to manipulate in the E V E N T L I S t e n E R interface, the defined methods must be performed in implementing this interface. This class is an event listener. For example: / * Define a mouse mobile event object * / public class mouseMoveDexampleEvent Extends java.util.EventObject {// In this class contains status information related to the mouse mobile event ...} / * Defines the mouse movement Event's listener interface * / interface mousemovedexamplelistener extends java.util.EventListener {/ * Defines how the mouse mobile event listener should support the method * / void mouseMovent MME);} Only the method is defined in the interface Name, method of parameters and return value types. As embodied mouse M oved method of the above interfaces are defined in the following A rbitrary O bject class: class ArbitraryObject implements MouseMovedExampleListener {public void mouseMoved (MouseMovedExampleEvent mme) {...}} A rbitrary O bject M ouse is M O Oved E Xample E VENT event listener. 4. Registration and logout of event monitors To allow various possible event listeners to establish an event stream between the source and event listeners, the event source must provide registration for event listeners. Logout method. In the previous Bound property introduction, this use process has been seen, in actual, event listener's registration and logout To use standard design format: public void add
First, we define an event listener interfaces: public interface ModelChangedListener extends java.util.EventListener {void modelChanged (EventObject e);} Next define the event source class: public abstract class Model {private Vector listeners = new Vector (); // define a memory array of event listener / * the above design format The positive event responder is not in the listener queue, and the action responders should be determined by the adaptation class. At present, most developments are generated when generating code, and event processing is made by adaptation classes. 2.2.3 Persistence When J Ava B EANS is userized within the construction tool, all of its states should be saved, and the next time it is loaded into the construction tool or during operation. It should be the last modified information. In order to do this, you want to save the information of certain fields of B E A N s, to define the J a V a. I O. S E R I a L I Z A B LE interface when defining B E a N s. For example: Public class button, {}, the information of the field in B E A N s in the serialization interface will be automatically saved. If information does not want to save some fields, the information of these fields prior to T R a N S I E N T or S T A T I C, T R A N S I E N T and S T A T I C variable cannot be saved. Typically, all disclosed attributes of a B e a n s should be saved, and the internal state can also be selected. B E a N S Developers When you modify the software, you can add a field, remove a reference to other classes, change a field of P R i v A T E / P R O T E C TETET ED E / P R, which does not affect the storage structure relationship of the class. However, when a field is removed from the class, change a variable in the location of the class system, change a field to transient / static, or it is transient / static, which is now changed to other features, will cause storage relationships. The change. J Ava B EANS The JAVA B EANS component is designed, generally in the Z IP format file stored in the extension JAR, contains information related to J Ava B EANS in JAR, and specifies in the Manifest file. Which classes are J Ava B Eans. Taking J a V A B E A N s stored in J a R file When transmitting in the network, the amount of data is greatly reduced, and some resources required for J a V A B E A N s are run together. Here, some internal characteristics of J a V A B E A N s S and its conventional design methods are referenced, and the J a V A B E A N s Specification is referenced. As the world's large I S v is more and more support for J a V A B E A N s S, the specification is still evolving in some details, but the basic framework will not change. 2.2.4 User-User J ava b EANS Developers can add a B EANS to describe a B EANS content, a B EANS, and B EANS. Users can use this information that came with B EANS in the constructor to usersize the appearance of B EANS and the action you should do. One B EANS does not have to have B Ean C USTomizer, P RPERTY E DITOR and B Ean I NFO, depending on the actual situation, these are optional. When some B EANS is more complicated, it is necessary to provide this information to Wi Zard's way The user of B Ean can customize a B EANS. Some simple B EANS may not have this information, then the constructor can use the self-contained perspective, fluor-out B EANS content, and display the information to a standard property list or event table for users to customize B EANS, ahead The B EANS's properties, methods, and event names mentioned in the section are named in a certain format, the main role is to make perspective for B EANS for development tools. Of course, it is also convenient to provide the programmer in a handwriting program to provide convenience, so that it can view its name and know it. 1. Severator Interface 32 Part 1 JSP Getting Started When a B E A N has its own customizer, you can display your own property table within the constructor. The J a V a. B E a N s. C U S TO M I Z ER interface must be implemented when defining the customizer. For example, following is a "button" B eans customizer: public class OurButtonCustomizer extends Panel implements Customizer {... ... / * table when implementing the general properties such as OurButtonCustomizer, which must be implemented in removePropertyChangeListener addProperChangeListener and, Thus, the constructor can add a monsoper with these functional code to attribute events. * / ... ... private PropertyChangeSupport changes = new PropertyChangeSupport (this); public void addPropertyChangeListener (PropertyChangeListener l) {changes.addPropertyChangeListener (l);} public void removePropertyChangeListener (PropertyChangeListener l) {changes.removePropertyChangeListener (l);} ...} 2. Property Editor Interface A J Ava B EANS provides a P Roperty E DITOR class to create an editor for the specified properties. This class must inherit from J a V a. B E a N s. P R o p E R T Y E D i T O R S Up Up P O R Type Class. The constructor does not directly use this class with the programmer of the handwritten code, but is instantiated and called this class in the B E A N i N f O of the next section. For example: public class MoleculeNameEditor extends java.beans.PropertyEditorSupport {public String [] getTags () {String resule [] = { "HyaluronicAcid", "Benzene", "buckmisterfullerine", "cyclohexane", "ethane", "water"} The RETURN RESULE;}}} The above example creates a property editor for the TA GS attribute. In the constructor, select M OLECule N AME from the drop-down table should be "H Yaluronic A ID" or "Water". 3. BeanInfo Interface Each B E a N i N f O class may also have the associated B E A N i N f O, which describes the appearance of this B E A N during the construction tool. B E a N I N f O Define properties, methods, events, display their names, providing simple help notes. For example: public class MoleculeBeanInfo extends SimpleBeanInfo {public PropertyDescriptor [] getPropertyDescriptors () {try {PropertyDescriptor pd = new PropertyDescriptor ( "moleculeName", Molecule.class); / * pd by a reference on the MoleculeNameEditor class, and returns the acquired moleculeName Property * / Pd.SetPropertyEditorClass (MoleculeNameEditor.class); PropertyDescriptor result [] = {PD}; return results; Chapter 2 Preparatory knowledge 33 } catCH (Exception EX) {system.err.println ("MoleculeBeanInfo: Unexpected EXEPTION: EX); Return Null;}}} 2.3 Java Servlet gives the JSP and Java Servlet close contact, the author believes that learning JSP must have Java The basics of servlet, of course, do not need to become a Java servlet, but must have conceptual understanding. The basic knowledge of Java servlet will be described below. For specific program development, it is now not required to immediately master it. The purpose of this section is to make readers can understand SE R Vl e t. 2.3.1 HTTP Servlet APIJAVA Servlet Development Tools (J S D K) provides multiple packages that need to be used when writing servlets. These include two basic packages for all servlets: javax.servlet and J a v a x. S e r v L e t. H t tp. Can now use J S D k 2. 0 from S u n company's WE B. Here mainly introduces the HTTP Servlet application programming interface provided by J r V L e t. H t t p. 1. Brief description Create an HTTP Servlet, you need to extend the HTTPServlet class, which is a subclass of the genericServlet for H T M L table data with a special method. The HTTPSERVLET class contains i n i t (), d e S T R O Y (), service (), etc. Wherein init () and destroy () methods are inherited. (1) Init () method In the life period of the servlet, only the init () method is performed. It is performed when the server is loaded with a servlet. The server can be configured to load S E R v L e t when the server or client is first accessed. No matter how many client access S E R V L e t, you will not repeat init (). (2) The service () method service () method is the core of the servlet. Whenever a customer requests an HTTPSERVLET object, the service () method of the object is called, and passes to this method a "SERVLET R Equest) object and a" SERVLET R Esponse) object. As a parameter. The service () method already exists in the HTTPServlet. The default service function is to call the corresponding DO functionality corresponding to the HTTP request. For example, if the HTTP request method is g e t, DOGET () is called by default. The servlet should overwrite the DO function for the HTTP method supported by servlet. Because the httpservlet.service () method checks if the request method is called to call the appropriate processing method, it is not necessary to override the service () method. Just override the corresponding DO method. (3) The destroy () method design method is only performed once, ie, execute the method when the server is stopped and unloading the servlet. Typically, servlet is turned off as part of the server process. The default destroy () method is usually in line with requirements, but it can also overwrite it, typically manage server-end resources. For example, if the servlet accumulates statistics at runtime, you can write 34 first part JSP entry. A Destroy () method, which is used to save the statistics in the file when the Servlet is not loaded. Another example is to turn off the database connection. (4) G E T S E R V L E T C O N F I g () Method G E T S E R Vl E T C O N F I g () method Returns a servletconfig object, which is used to return initialization parameters and S E R V L E T C O N t e x t. The servletContext interface provides environmental information about servlet. (5) GE T S E R V L E T I N f O () Method G E T S E R V L E TI N f O () method is an optional method that provides information about servlet, such as author, version, copyright. When the server calls the SEVLET SERV i C e (), D O g e t (), and D O P O S (), "request" and "response" are required as parameters. The "Request" object provides information about the request, and the "response" is provided with a communication path that returns the response information to the browser. The relevant class in the Javax.Servlet package is S e R V1 e t R e t R e q u e s t, and the related class in the javax.servlet.http package is HTTPSERVLETREQUEST and H T T P s E R V1 E T R E S P O N s E. Servlet communicates with the server through these objects and eventually communicates with the client. The servlet can know the information of the client environment, the information of the server environment and all the information provided by the client by calling the "RE Q u e s T) object method. S e r V L e t can call the "response" object to send a response, which is ready to send back the client. 2. Common HTTP Servlet API Overview Supports the HTTP protocol servlet to use Javax. Servlet. HTTP package for development, while core functions in the Javax. Servlet package provide many classes and functions developed by WE B, providing JSP development brings It is very convenient. For example, the abstract h TTP SERVLET class contains support for different HTTP request methods and header information, H TTP SERVLET R Equest and H TTP SERVLET R ESPONSE interfaces allow direct communication with WE B servers, and H TTP S Ession provides built-in sessions Tracking features; C Ookie classes can quickly set up and process HTTP cookies, H TTP U TILS class is used to process the request string. (1) CookieC O O K I E provides a convenient way to read, create, and manipulate HTTP cookies, allowing S e R V L e t to store small amounts of data on the client. C O O K i e is mainly used for session tracking and storage of a small number of user configuration information data. The SERVLET acquires COKIE information with the Get C Ookie () method of the H TTP SERVLET R Equest; H TTP SERVLET R ESPONSE's Add C Ookie () method sends a new C Ookie to the client because it is set to use the HTTP header. Therefore, Add C ocie () must be called before any output is sent to the client. Although Java Web Server has a S u n. S E R V L e t. U T i l. C O o K i E class can complete the substantially the same work, but the initial servlet API 1.0 does not have a C O O K i e class. S u n. s E r V L E T. The only difference between C O o K I E and current C O o K I E class is the interface of the C O O K I E class, rather than the interface of the H t t p s e r Vl e t R e q u e S and H T T P S e R V1 E T R e S P O N s E. (2) HTTPSERVLETH T T T P S E R VL E T is an abstract class for the development of the HTTP Servlet framework, wherein the S e R V i c e () method assigns the request to the Protected Service () method of the H t tp. (3) HTTPSERVLETREQUESTH T t p S e R V L E T R E Q u E S T provides additional functions for HTTP servlets by extending SE R groups. It supports the function of C O O K i E S and S E S I O Ni Tracking and Getting the H T T T, and the H t t p s e r V L e t R e q u e s t can also resolve the form data of H T T P P, and store it as S e r V L e t parameter. Chapter 2 Preparatory Knowledge 35 The server transmits the H t t p S e R Vl E T R e q u e s T object to the S E R V I c E () method of H T T P S e R Vl e t. (4) HTTPSERVLETRESPONSEH T t p S E R V L E T R E S P O N S e-extended S E R V L E T R E S P O N S E Class, allows the H T T T P Protocol related data, including the response head and the status code. It defines a range of constants for describing various H t t p status codes, as well as a help function for S e s S i O n trace operation. (5) HTTPSESSIONH T T T P S E S S I O N interface provides a certification mechanism for WE B visitor. The H t t p s e s S I O n interface allows S e R V L e t to view and manipulate session related information, such as creating access times and session identification. It also contains some methods for binding sessions to specific objects, allowing "shopping carts" and other applications to save data for all connections, without having to save databases or other E x T R A - S E R V L e T resources. The g e t-e t-e-T T T P SE RV L E T R e q u e t-t, which is called, to obtain the behavior of the H T T P S E S I O N, such as the time waiting for S e S I O N, depending on the server. Although any object can be bound to S E S I O N, but the busy SE R v L e t is binded to the SES S I O N will increase the burden on the server. Reducing the server burden is the most commonly used solution is to bind only the object used to implement J a V a. I O. S e R I a L I z A B LE interface (it contains all data type objects in the Java API core). Some servers can write S E R I A LET to disk, U N S E R I a L I Z A B LE object, such as J a V a. S Q, C O N e c t i o n, must be retained in memory. (6) HTTPSESSIONBINGEVENTH T T PS E S I O N E N D I N G L I S TE E N E R Listening Object Binding or Disconnection Binding The H T T P S E S I O N B I N D I N G E V E N T is transmitted to the H T T P S E S I O N B I N D I N g L I S TE E n E R. (7) HTTPSessionBindingListener When the object is bound to the H t t p S E S I O N or release the binding from the H t t p S e s S I O N, the interface is notified to implement the interface for implementing the H T T P SE S I O N B I N D I N g L I s E n e n E R by calling valuebound () and valueunbound (). In other cases, this interface can be sequentially cleared from the resources associated with S E S I O N, such as database connections, and the like. (8) HTTPSESESSIONCONTEXTH T T T P S E S I O N C O N T E X T provides a method of accessing all active S e s S I O N on the server, which clears the un active S e S I O n to the SE RV L e t, which is useful to display statistical information and other sharing information. S e R V L e t obtains the H T T P S E S I O N C O N TEEx T TI object by calling the GetSessionContext () method of H T T P S E S I O N. (9) HTTPUTILS This is a container object that houses many useful H t-T p methods that use these methods to make S E R V L E T development more convenient. 2.3.2 System Information To successfully establish WE B applications, you must understand the operating environment it needs, and also understand the specific situations of the server that executes S E R V L E T executes S E R V L E T and sending requests. Regardless of the environment where the application is running, it should be exactively a request information that the application should process should be processed. There are many ways to get this information in S E R V L e t. In most cases, each method returns different results. Compare the environment variables of C G i for transmitting information, the reader discovers that the S e R v L e t method has the following advantages: 36 Part 1 JSP Getting Started • Powerful Type Check. • Delay calculation. • Interact with the server. 1. Initialization Parameters Each registered servlet name has specific parameters associated with it, the servlet program can get these parameters at any time; they often use the init () method to set the initial or default value for the servlet Degree to custom Servlet behavior. (1) Get the initial parameter S e R V L E T Use G E T I N I TP A R A M E TET () method to acquire the initial parameter: Public String ServletConfig.GetInitParameter (String Name) This method returns the name or null value of the initial parameter (if not there). The return value is always the S t R i n g type, which is explained by S e R V L e t. G e n E R I C S E V L E TEAFE FIE Interface Direct Access G E TET I N I T P A R A M E T E R () method. (2) Get the initial parameter name servlet call GET I NIT P ARAMETER N AMES () method You can verify all of its parameters: public enumeration servletconfig.getinitParameterNames () This method Return value is the enumeration type or null value of the string object (if No parameters), often used for the debugging of the program. G e n e R I C S E R V L E T can also make S E R V L E TH directly access this method. 2. Server S e r V L e T can understand most of the information of the server. It knows the host name, port number, server software, and other information. S e R V L e t can also display this information to the client to customize the client based on the behavior of a specific server packet, and even clear the behavior of the machine to run S E R V L e t. (1) The server-related information S E R V L E T Gets information of the server by four methods: two are called by S e R v L e t R E Q U E E R V1 transmitted to S E R V L E T, two from S e R Vl E T C O N TE E X T Object Call, S E R V L E T C O N TEx TEM contains the operating environment of S E R V L e t. By using the method GET S ERVER N AME () and GET S ERVER P Ort (), the s ervlet can obtain the name and port number of the server for the specific request separately: public string servletRequest.getServerName () public int servletRequest.getServerport () SERVLET C ontext G etco G etco () and get a ttribute () method Provide information about server software and attribute: public string servletContext.getServerInfo () public object servletContext.getaattribute (String name) (2) Lock servlet to server utilization Server information can complete many special features, such as writing a servlet, and do not want it to run everywhere, maybe you want to sell, limit those unauthorized copies, or want to lock the servlet to the client through a software certificate. Another situation may be that the developer has written a certificate for S e R v L e t and wants to ensure that it runs behind the firewall. This is not difficult to do because S e R V L e t allows timely access to the server. 3 The client is for each request, and S e R V L e t acquires information about the client, requiring authentication, and actual users. These information can be used for the second chapter preparatory knowledge 37 To log in to access, collect user personal data or limit access to certain clients. (1) Get client information servlet available GET R EMOTE A DDR () and GET R EMOTE H OST () Get the client's IP address and host name, respectively: public string servletRequest.getRemoteAddr () public string servletRequest.getRemotehost () or above Both methods returns a string object type. This information comes from the S O c k e t port connecting the server and the client, so the remote address and the remote host name may be the address and host name of the proxy server. The remote address may be "1 9 2. 2 6. 8 0. 11 8", and the remote hostname may be "D i s t. E N g r. S g i. C o m". I Net A Ddress. Get B Y N AME () method can convert the IP address and the remote host name into Java. Net. I Net A Ddress object: inetaddress remoteinetaddress = inetaddress.getbyName (Req.getRemoteAddr ()); (2) Limit to only the machines that allow only certain regions to access the US government's restriction policy for good encryption technology exports, on some WE B sites, the allowable software is particularly cautious. This limitation can be strengthened well with the function of acquiring client information using S e r V L e t. These S e R v L e T can check the client and links those machines from the United States and Canada. For business applications, you can determine that a S e R V L e t is only available to client services from the intranet network to ensure safety. (3) Get user-related information If you want to make further restrictions on Web Pages, not based on geographical restrictions, what to do? For example, published online magazines, just want to let the orderless users can access. The reader may say that this is good, I can do it, I don't have to use S E R v L e t. Yes, almost every H t t p server embeds this feature, which can limit a particular user to all or some web pages. How to set limits differ depending on the server you are using, here we give their common working mechanism. When the browser first tries to access a page, the server will give the browser a response to authenticate. After the browser receives this response, a dialog box requesting to enter the username and password will pop up. Once the user enters information, the browser will try again to access the page again, but the user name and password information are attached in this request information. After the server accepts the username / password pair, it will handle this request; if the server does not accept this username / password pair, the browser access is rejected again, and the user must re-enter. So, how does S e r v L e T are processed? When visiting the restricted servlet, the servlet can call the Get R Emote U Ser () method, get the server-approved user name: public string httpservletRequest.getRemoteuser () SERVLET can also use Get a uth Ty PE () method to obtain authentication types : Public string httpservletRequest.getAuthType () This method returns the authentication type or an air value (if not restricted), the most commonly used authentication type is "Basic" and "Digest". (4) Personalized welcome information A simple call G e t R E M O TETETET SE R () method can be asked to him by styling user name and remembers his last login time. However, it should be noted that this method is only applicable to authorized users. For unauthorized users, S E S I O N can be used. 38 Part 1 JSP Getting Started 4. Requests how to get SE R v L e t How to obtain information about servers and clients, now you have to learn truly important content: S e r v L e t Howy knows what the customer requests. (1) Request parameter Each access to S e R V L e t can have many associated parameters, which are typical name / value pairs, which are used to tell SE RVL E t for additional information required to process the request. Thousands should be given to mix the parameters herein with the previous parameters related to the S E R v L e T itself. Fortunately, even if servlets have to get many parameters, get the way each parameter is also the same, namely Get P Arameter () and GET P Arameter Va lues () method: public string servletRequest.getParameter (String name) public string [] PUBLIC STRING [] ServletRequest.getParameterValues (String Name) Get P Arameter () Returns Named Parameters in a string. If you do not specify a parameter, return null values, and return values must be guaranteed to be a normal encoding. If this parameter has multiple values, this value is related to the server. In this case, the GET P Arameter Va lues () method should be used, this method returns all values of the corresponding parameters in the form of the character object array, if not specified Of course, it is null. Each value returned to a unit length in an array. In addition to getting parameter values, servlet can also use GET P Arameter N Ames () to get parameter name: public enumeration servletRequest.getParameterNames () This method returns a parameter name in string enumeration type, or return null values when there is no parameter . This method is often used for program debugging. Finally, the servlet can also obtain the requesting binary string with the GET Q ury s TRING () method: public string servletRequest.getQueryString () This method returns the requested binary string (the encoded Get parameter information), if there is no request string Then return null values. These underlying data are rarely used to process form data. (2) Publish a license key If you are now prepared to write a servlet to the specific host and port number to release the K Eyed SERVER L OCK license key, the key acquired from the servlet can be used to unlock the K eyeed SERVER L OCK servlet. . So how do you know that the host name and port number of S e r v L e t is unlocked? Of course it is the request parameter. (3) Path information In addition to parameter information, the H t t p request can also include "additional path information" or "virtual path". Typically, the additional path information is a path for indicating the files you want to use by Servlet, usually in the form of URLs requested by HTTP, possibly like this: http: / / / server: port / servlet / vi EW f Ile / INDEX HTML This will activate the ViewFile Servlet while delivering "index. html" as additional path information. S e R V L e t can access this path information, and convert the string "I N D e x. H t m L" into the real path of file I n d x. H T M L. What is the true path of "/ i n d e x. H t M L"? It refers to the full file system path returned by the server directly as the customer requests "/ i n d e x. H t ml" file. May be D O c u m e n t _ R O O T / I N D e x. H tml, of course, the server may also change it with an alias. In addition to specifying in the form of a clear U R L, additional information can also be written into the form of a c t i o n parameter in the H t m L form: the second chapter preparation knowledge 39
The digital state code is usually accompanied by "reason", and it is easy to understand. Typically the status code works in the background and interprets the browser software. Sometimes, especially when mistake, the browser displays the status code to the user. The most common status code may be "404 Not Found", when the server cannot locate U r, it will send this status code. Response body is the main content of the response information, for the H t m L, the responsive body is H T M L itself. For the picture, the responsive body is byte that makes up the picture. Responsive body can be any type and any length; the client knows what the received by explaining the H t t p on the response information. Ordinary S e R V L E T is simple to http servlet - it only returns to the user. However, Getting Started with G E N E R I C S E R V L E T Subclass 44 Part 1 JSP
It is possible to divide a small part of a fine portion with A P i, which seems to be returned to a plurality of items. In fact, this is the work you have to do. At the bottom layer, the server will respond to the client in the form of a word stream, any way to set the status code or header is abstraction on this basis. Understand this is important, because even if S E R V L e t programmer does not have to know the details of the H t t p protocol, the protocol does not only call the method of calling the method. In particular, the H t t p protocol premises status codes and heads must be sent before responding. Therefore, S E R V L E T Always set the status code and head before sending any responsive body. Some servers, including Java Web Server, cache some servlet responders (usually about 4k) - This allows a certain degree of freedom to set the status code and header if the servlet has a shorter responsive body. . However, these behaviors are all servers, and a wise S e r v L e t programmer should forget all. 2. Sending standard response information S E R Vl E T R E S P O N S E () method can set the content of the response to the specified M i ME type type. Public void servletResponse.setContentType (String Type) In HTTP Servlet, this method is used to set C O N T E N T - TYPE HTTP header. G etc ore () method Returns a P RRINT WR ITER object for writing a character-based response data: public printwriter servletResponse.getWriter () throws owception This Writer is characterized by characterization of the character set in the content type, if not Specified character set (this is a common thing), Writer will be encoded with ISO - 8 8 5 9 - 1, ISO - 8 8 5 9 8 - 1 is mainly used for Western Europe. The character set will be mentioned in the following chapters, so you now just set the type of content before you get P R I N T WR I T, before you get P R I N T WR I T. If G e t O U T P U Ts T R E A M () has been called by this response, this method will throw I L E g A L S T a T E E X C E P Ti O N abnormality; if the encoding form of the output stream is not supported or unknown, throw U N S U N g e x C e p T I O N abnormally. In addition to returning with P R I n t WR I T E R, S e R V L e t can also write binary data with the special subclass of J A V. I O. O U T P U T S R E a M, which is defined in J a V1. S E R V L e t. You can get a SERVLET O UTPUT S TREAM object with the GET O UTPUT S TREAM () method: public servletoutputstream servletResponse.getputstream () THROWS IOEXCEPTION This method returns a SERVLET O UTPUT S TREAM class object, used to write binary (one word Section) Response data.
Do not make any encoding. If G E T WR i T E R () has been called for this response, this method will return an abnormality of I L E g A L S t a t e e x c e p T I O N. S e r V L e t O U T P U t R E a high like a standard Java PrintStream class, in Servlet API V1.0, this class is used for all S E R V L E T output, which is both a text type, but also a binary type. In Servlet API V2.0, it is only used to process binary outputs. Since it is a direct subclass of O U T P U t R E A M, it has W R I T E (), F L U S H (), and C L O S E () method of O U T P U T S T R E A M. To solve this problem, it adds its own P R I n t (), P R I n t n () method for writing most of the J a V A original type of data. The difference between the S e R V L e t O U T P U t ral e a m interface and the P R I n t R e A m interface is that the P R I n t () and P R I n () and P R I n () and P R I n t () methods of S E R E T O U T P U T S R E T O U T P U T S Rism Data cannot be explicitly displayed data of OB J E C T or C H A R []. 3 Use a continuous connection to continuous connection (sometimes referred to as "K E E P - A L I v e" connection) to optimize S E R V L e t to return content to the customer. To understand its optimization mechanism, you must first understand how the H t t p connection works. The basic concepts of this will be partially explained. When customers, such as browsers, want to request a WE B document from the server, first create a second chapter of S O c k e t with the server 45
connection. With this connection, the client can issue a request and receive server response. The client sends a blank line represents the completion request. In turn, the server indicates that the response has been completed by turning off the S O c k e t. It's that simple. But if the page received the page contains the tag or tag, the client will request more content from the server, what should I do? So another Socket, if a web contains 1 0 pictures and an applet consisting of 2 5 classes, you need 3 6 connections to transfer this page (of course, you can now pack these classes using JAR files. Reduce the number of connections). No wonder someone is called W W W for Word Wide Wa I T! . A preferred method is that the same S O c k e t connection receives more web content, and sometimes this technique is called continuous connection. The key to the continuous connection is that the client and server must be agreed with the end of the server's response to the client starting next connection. They may use an empty line as a sign, but what if the response information itself contains a space line? The working mode of continuous connection is that the server sets C O N t e n t - l e n g t h head in response to this responsive body. The client will only control the next S O C K e t connection after receiving this response body. Most servers can handle C O N t-heads of the files that they serve, but different S E R V L e T is different. SETVLET can use the set c ontent l ength () method to process the continuous connection of dynamic content: Public void servletResponse.setContentLength (int LEN) This method returns the length of the server response content, in the HTTP Servlet, this method sets http content- L ength head. Note that the use of this method is optional, however, if the SE R Vl E T will make full use of the advantages of continuous connection, the client can also accurately display process control. When the S e t c o N t e n t1, there is two points to note that: S e R V L E T must call this method before transmitting response information, and a given length must be precise. Even if there is only one byte error, it may have problems. This seems difficult to do it, in fact, S e r v L e t uses B Y t e a r r a y o U T P U t again to cache the output. The servlet is not written by the response information to the P RRIT WR ITER returned by GET WRITER (), but is written to the P RRIT WR ITER based on B Yte A Ray O Utput S Tream. This array will output with servlet. Growth. When S e R V L e t is ready to exit, it can set the length of the content to a cache size and send content to the client cache. Note that bytes are transmitted based on S e R Vl E T O U TP U T R. Do this simple modification, S e R v L e t will use the advantages of continuous connection. Continuous connection is to pay for a price. This is important. Cache All outputs and batch send data require more memory, and it is possible to delay the time point of the client to start receiving data.
For SE R V L e t for a shorter response, it is acceptable; however, the cost of the SE R Vl E T, considering the memory overhead and delay, may not establish several connections. It is also important to pay attention to all S e R v L e t supports continuous connection. That is, the content length of setting S E R V L E T response is a good choice, which is supported by the server that is supported, but is ignored by other servers. 4. Generate H T M LH T M L Generate Pack for S E R V L E T provides a series of classes, which abstract many details of H T M L, especially the label of H T M L. The extent of the abstraction depends on the package used: Some very little H t M L tags, leaving some basic details (such as opening and closing the H t M L tag) to programmers. With this class of bags, it is similar to handmade H t m L, which is not discussed here. Another class is well abstracted by the specific content of the H t m L, while the H t m L is a collection of J a V A objects. A web page can be seen as an object, which can contain other H t m L objects (such as lists, tables), and more to include more H t m L objects (such as list items and table units). This object-oriented method can greatly simplify the generation of H T M L, and make S E R V L e t easier to write, maintenance, sometimes more efficient. 46 Part 1 JSP Getting Started
Generating Hello WO R L D is an ordinary Hello World Servlet, as a simplest S e R v L e t, I believe that the reader can understand it through the previous learning. Import java.io. *; import javax.servlet. *; import javax.servlet.http. *; / ** hello world! servlet class * / public class helloworld extends httpservlet {/ ** doget method overload, for the client process GET request * / public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {response.setContentType ( "text / html"); PrintWriter out = response.getWriter (); out.println ( " "); out.println ("
"); out.println (" "); out.println ("