JSP Advanced Programming 2

zhaozj2021-02-08  209

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 > right shift (With symbol)>>> Add to change the number of points. Press zero. Swissing and molding abide by the following equation: (A / B) * b (a% b) == a. An abnormality of integer arithmetic operation is Due to zero or press the zero molding. It will trigger an arithmetic abnormality, down overflow to generate zero, overflow causes the offline. For example: add 1 exceeding the maximum value, after the mold, turn to the minimum. A OP = assignment Operators, and each two-purpose integer operator in the table, constitute an expression. Integer relationship operator <,>, <=,> =, = = and! = Generates a Boolean type data. (3) Boolean variables or combinations of Boolean variables or expressions can generate new Boolean values. Unicom operators! It is Boolean. Big Operators &, | and ^ are logical and xor operators, they Forced two operations to ask for Boolean value. To avoid the right operand redundancy evaluation, the user can use short-circuit evaluate operators && and | Users can use = = and! =, Assignment operators can also be used & = , | =, ^ =. Trinary condition operator?: The same as the C language. (4) Floating point operator floating point operator can use a combination of conventional operators, such as single operators , - , Binocular operators , -, *, and /, and assignment operators =, - =, * =, and / =. In addition, there is a molding operation:% and% = can also be used for floating point numbers, such as : A% B and A - ((int) (a / b) * b) The semantics is the same. This means that the result of A% B is removed from the remaining floating point portion. Only single-precision operation floating point expression According to the single precision operation, the single-precision result is generated. If the floating point expression contains one or more double precision operands, the result is the double precision floating point. (5) array operator array The operator is as follows: [] can give the value of an element in an array. The legal range of values ​​is reduced from the length of the 0 to array. 1. The check range is only implemented at runtime. (6) Object operator Big Operator InstanceOf Tests if an object is an instance of the specified class or its subclass. For example: IF (MyObj ECT InstanceOf myclass) {Chapter 2 Preparation Knowledge 19

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) {}} This class must be defined as the A b S T R A CT class when a class contains an A b S R. However, not all member functions of the A b S T R a C T class are A b S T R a C t. The A b S t R A C T class cannot have a private member function (they cannot be implemented), and there is no static member function. 2.1.7 Interface When it is determined that multiple classes are very similar, the member function of the A B S T R A C t is useful. But if you need to use this A b S T R a C t member function, you must create a new class, which is sometimes cumbersome. The interface provides an advantageous method of abstract member functions. An interface contains the collection of member functions implemented in another place. The member function is defined in the interface as P UB L i c and A B S T R a C T. The instance variable in the interface is P UB L i C, S T a L. The main difference between the interfaces and abstractions is that an interface provides a method of encapsulating a function protocol without having to force the user to inherit the class. For example: public interface audiclip {file: // start playing the clip.void play (); file: // Play the clip in a loop.void loop (); file: // stop playing the clipvoid stop ();} Use the Audio Clip interface to use the Implencents keyword to provide program code for the member function. Class MyClass Implements Audioclip {Void Play () {} Void Loop } Void Stop }} The advantage is that an interface class can be implemented by any more class, each class can Sharing program interface without having to care about how other classes are implemented. 2.1.8 Package (P A C K ​​a g e) consists of a set of classes (C L A S s) and the interface (I N T E R f A C). It is a tool for managing large namespaces to avoid name conflicts. The names of each class and interface are included in a packet. According to the general habits, its name is composed of "." Separated words, the first word is usually the name of the organization that develops this package. Define a package of a compilation unit definition by P A C K ​​A G E statement. If you use a P a c k a g E statement, the first line of the compiler must have no space, and there is no comment. The format is as follows: 24 Part 1 JSP Getting Started

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 ( listener; public void remove ( listener); for example: 30 Part 1 JSP Getting Started

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 that is here below ModelChangedListener * / public synchronized void addModelChangedListener (ModelChangedListener mcl) {listeners.addElement (mcl);} file: // the listener registered listeners into an array public synchronized void removeModelChangedListener (ModelChangedListener mcl) {listeners.removeElement (mcl); file: // the logout listener from the listeners} / * in front of two or more methods are labeled synchronized, because When running in a multi-threaded environment, there may be several objects at the same time to register and log out, using synchronized to make sure that they are synchronized. Development tools or programmers use these two ways to create event streams between source and listeners * / protected void notifymodelchanged () {/ ** Event source uses this method to notify the listener ActOlChanged event * / Vector L; EventObject E = New EventObject (this); / * First, copy the listener to the L array, freeze the status of EventListeners to pass the event. This way to ensure that the corresponding method of the target listener that has received the event is not effective before the event is passed to all listeners. * / synchronized (this) {l = (vector) listeners.clone ();} for (int i = 0; i

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

Word to look up:

Form Activate Dictionary Servlet Processing Request Tasks, and deliver additional path information "DICT / Definitions. TXT". Servlet uses words definitions to find the definitions. txt file, if the customer requests "/ DICT / Definitions. TXT" file, at the same time in Server _ root / public _ html / dict / definitions. TXT also exists, the customer will see the same file. . 1) Get path information. S E R V L E T can obtain additional path information with G E T P A T H i N f O () method: public string httpservletRequest.getPathInfo () This method returns an additional path information related to the request, or returns null value without given it. SERVLET usually needs to know the real file system path of a given file, which has a GET P ATH TR ANSLATED () method: public string httpservletRequest.getPathTranslated () This method returns an additional path information that has been converted to a real file path, or Annual value is returned when there is no additional path information. The path returned must point to the existing file and directory, the transformed path may be: "c: / j a v a WE B S E R V E R 1. 1. 1 / public_html / dict / definitions.txt". 2) Special path conversion. Sometimes, servlets need to use the Get R Eal P Ath () method to complete this task in the path of the additional path information: Public String ServletRequest.getRealPath (String Path) This method returns any given "virtual path" Real path, or return null value. If the given path is "/", this method returns the root directory of the server document; if the given path is G E T P a T H i N f O (), the return path is the same as the return value of the G E T P A T H Tr A N S L A T E D () method. GENERIC Servlets and HTTP Servlets can use this method, and there is no associated function in the CGI. 3) Get the M i M e type. After servlet knows the file path, you often need to know the file type, you can use the Get M IME TY PE () method to do this: public string servletcontext.getMimimeType (String file) This method returns the MIME type of the specified file, or not Return null values ​​in the case of knowing. Sometimes, "TE E X T / P L A I N" is returned when the file does not exist.

Common file types are: "T E X T / H T M L", "T E X T / P L A I n", "I m A g E / G I f" and "I m A g E / J P E g". Below this statement code acquires the MIME type of additional path information: string type = getServletContext (). GetMimeTranslated ()) (4) Service file Many application servers, such as WE B L OGI, using servlet to handle each request This is not only the advantage of Servlet processing, but it has brought great convenience to the modular design of the server. For example, all files are served by C O m. S u n .s e r v e R.http.fileservlet servlet, this S e R V L e t is registered under F I L E and is responsible for processing "/" alias (which is the default file requested). (5) Determine the requested content 40 first part JSP entry

S e R V L e t can use several methods to obtain the exact file requested by the customer. After all, the most rooted S e r v L e t will be a direct request to the target, in a long S e R v L e T chain, each S e R V L e t can only have a connection. There is no way to return to the original URL, Javax. Servlet. Http. Http. Http. H TTP URL () method of the customer is used to complete similar work: public static stringbuffer httputils.getRequest REQ) Method Based on the variable information of the H TTP SERVLET R Equest object, the reconstructed request URL, it returns the S TRING B u ff ER type, contains the architecture (like http), server name, port number, and additional path information. The URL after reconstruction should be very similar to the U r L requested by the customer. The difference between them is very fine (such as the space formation% 2 0 in the client side, but is " " at the server side). Since this method returns the S t R I n g b u FF E R type, U R L can be effectively modified (for example, additional query parameters). This method is often used to create redirect messages and report errors. In most cases, the servlet does not really need the URL requested, but the URI is required, it is returned by the method GET R Equest URI (): public string httpservletRequest.getRequesturi () This method returns a unified resource marker (URI) For normal HTTP servlets, a URI can be seen as a URL subtracting the architecture, host name, port number, and request string, but contains some additional path information. (6) Request Mechanism In addition to the content of the request, S e R V L E T has a method for obtaining how to request. G E T S C H E M E () method for returning the requesting frame: public string servletRequest.getscheme (), "h t t p", "H T T P S", and "F T P", as well as "J d B c" and "R M I" unique to J a V a. Although C G i also has a variable S e RV E R_ U R L, which includes a frame, but does not correspond to the function corresponding to G E T S C H E M E (). For HTTP Servlet, this method indicates that the request is securely connected to the S S1 (represented by "H T T T P S", or is represented by "H T T P"). G E T P R O T O C O L () Method Returns the protocol and version number for the request: Public String ServletRequest.getProtocol () protocol and version number are separated by slashes. If the protocol type cannot be determined, the null value is returned. For HTTP Servlet, the protocol is usually "V H T T P / 1. 0 V" or "V H T T P / 1. 1", the HTTP Servlet can use the protocol version to determine if the client can use the new features of HTTP 1.1.

To get the method used by the request, servlet calls get m ethod (): public string httpservletRequest.getMethod () This function returns the HTTP method for the request, including "get", "post", "head", H TTP S Ervlet Implementation Function Service () Disgument request tasks with this method. (7) Request head H t t p requests and responses have many content related to the HTTP header. These heads provide some additional information related to request (or response). The HTTP 1.0 protocol provides more than a dozen heads, and HTTP 1.1 is more. The complete discussion of the head is outside the scope of this book, which describes the heads of S E R V L E T most often access. S e r V L e t rarely needs to read an HTTP header when performing a request, and many of the headers associated with the request are processed by the server. This second chapter preparatory knowledge 41

Lifting a server how to limit an example of access to certain documents, the server uses the H t t p-head, and S e R v L e t does not understand the details. When the server receives a request to access the restricted page, it checks the request with the appropriate authentication information header. This head should contain legal usernames and passwords. If not, the server issues the header containing WW W- a uthenTicate, telling browsing The access to the resource is rejected. If the request is sent by the customer contains the correct authentication head, the server authorizes access and allows the activated servlet to obtain the user name through the Get R Emote U Ser () method. 1) Access the header. The H t t p header value can be accessed via H t t p s e r v L e t R e q u e s T object. Using Get H EADER (), Get D Ata H EADER () or get i NT H EADER () method, you return to S TRING type, long type, and int type data: public string httpservletRequest.getHeader (String name) Public long long httpservletRequest .getdateHeader (String name) Public int httpservletRequest.GetInTheader (String Name) Get H EADER () method Returns the value of the specified head in the S TRING type, if the head is not part of the request, return null values, all types of heads This method can be used. G E T D A TET EH E A D E R () Returns the value of the L O N g type, indicates the date, and if the head is not part of the request, Return - 1. This method throws an I l L E g A l A RG U m E n t e x C e p T I o n when the head value cannot be converted to D A TE. This method is very useful when treating L A S T - M O D I f E d and I F - M O D i f i e d - s i n c e. G etc i nt h eader () returns an integer value or - 1 (if the component is not sent as a request), this method throws N Umber F ORMAT E when the called head cannot be converted into an integer. Xception is abnormal. If you can use G e t h e a d e r n a m e s () access, S e R V L e t can also obtain all header names: public enumeration httpservletRequest.getHeadernAmes () This method returns the name of all heads with the enumeration type of the S t R i N g object. If there is no head, return to the empty enumeration type. 2) Head information in the servlet chain. The servlet links an interesting loop that handles the servlet header information, unlike other servlets, the servlet in the chain or the chain is not read from the customer request, but is read from the response information of a servlet. Head information value. The powerful and flexibility of this processing method comes from the fact that SE R Vl e t intelligently handles the output of the previous S E R V L E T, not only in terms of content, but also in terms of header information. For example, it can add some additional header information to the response information or change the existing header information. It can even prohibit the header information.

However, this powerful function is to be responsible: unless servlet explicitly reads the response header information of the previous servlet, and as part of its own response information, this header will not be sent, the client Can't see this information. The normal chain S E R V L e t will always pass the head of the previous S E R V L E T, unless there is a special reason to handle anything else. (8) Input flow, each request with the servlet has a relevant input stream, just like the servlet writes the associated response object to the P RRINT WR ITER or O UTPUT S TREAM, the servlet can also be from R EADER. Or read the information related to the request in i NPUT S TREAM. The data read from the input stream can be any data type and any length. There are three functions of the input stream: 1) In the servlet chain, pass the previous servlet's response information down; 2) Content related to the POST request Pass to HTTP servlet; 3) Pass the binary information sent by the client to the non-http servlet. 42 Part 1 JSP Getting Started

To read character data in the input stream, you should use the Get R EADER () method, and return B u ff erd R EAder class object: public buffreader servletRequest.getReader () throws ioException uses B u ff Ered R EADER as returned The advantage of the data type is that it can correctly convert in various character intervals. If Get I NPUT S TREAM () is called before the same request, this method throws i Llegal S Tate E Xception, if the input character is not supported or unknown characters, throw U NSUPPORTED E NCODING E Xception Exception . To read binary data from the input stream, you have to use the GET I nPut S Tream () method and return to the SERVLET I NPUT S TREAM Type: Public ServletInputStream ServletRequest.getInputStream () THROWS IOEXCES ERVLET I NPUT S TREAM is I NPUT S The direct subclass of Tream can be processed as normal I NPUT S TREAM, and the ability to read data in a single line. If G e t R e a d e r () is called before the same request, this method throws I L E G A L S t a t e EE x C E P Ti O N abnormality. Once you have SERVLET I NPUT S TREAM, you can use read l ine () to read: public int servletinputstream.readline (byte b []t "(byte b []t) (byte b [], int off, int LEN) throws ioException This method will use Bytes from the input stream In the byte array B, the start is given by O ff, or when '/ n' is encountered or the LEN byte is read. At the end of the end, "/ N" is also read into the cache. This method returns to the number of bytes that has been read, or returns - 1 when reaching the end of the input stream. SERVLET Using Get C ontent Ty PE () and Get C ontent L ENGTH () Get the content type and data length transmitted by the input stream, respectively: public string servletRequest.getContentType () public int servletRequest.getContentLength () Get C ontent Ty PE () Method Returns the transmission content type of the input stream, or returns null value (if the type is unknown, such as no data); get c ontent l ength () returns the length of the byte calculation, if the type is unknown, return - 1.1 ) Build a servlet chain with an input stream. The SE R Vl e t in the chain receives response information by the input stream in one S e R V L e t. 2) The input stream processes the P O S t for. When S e R Vl e t processes the P O S t, the case where the input stream is used to access the P O S T data is very small. Typically, P O S T data is only the parameter information, and S e R V L e t can easily obtain it with G E TP A R A M E TER () method.

S e r V L e t can check the type of input stream to identify the type of P O S T, if it is a P P L I C A T I O N / X - W W W - F O R M - U R, and the data can be obtained from the G E T P A R A M e T E R () method or similar method. S e r V L E T should call G E T C O N T L e n g t h () before calling G E T P A R A M e TE R () to avoid being rejected. Malicious customers may send unreasonable huge data when sending P O S T, attempting to call the speed of the server to the slowest when the G e t p A r a m e t eR () method is called at S E R V L E T. S e R V1 T can verify the rationality of the data length, or limit less than 4 K as a precautionary action by G E T C O N TE E N T L E N g t. 3) Receive files with the input stream. S e r v l e t can receive upload files using the input flow. Before explaining, it is important to remind: uploading files are experimental, and not all browsers are supported. Netscape Navigator starts support file upload from Internet Exploer4.0 from 3. 0, Microsoft. Chapter 2 Preparatory Knowledge 43

Simply, any number of files and parameters can be transmitted as formats in a single POST request, and the POST request format is different from the format of the standard Application / X - WWW - form - Urlencoded, so it is necessary to set the type to Multipart. / form - data. The client program uploaded by the file is quite simple. The following H t M L will send a form to ask the user name and the file to be uploaded. Note that e n c t y p e attribute and the use of F i l e input types. What is your name?
Which file do you want to upload?
How to implement file upload, please see Chapter 11 of this book. (9) Additional attributes Sometimes S E R V L E T requires other information requested, and this information cannot be acquired by the method mentioned earlier, at which time the last move, that is, G E T A T R I B U t E () method. I still remember how the S e r V L E T C O N t e n T has a G e () method how is the attribute of a particular server? S e R V1 T r e q u e s T also has a G e t a t t R I b U t e () method: Public Object servletRequest.getattribute (String name) This method returns a null value if the server does not support the specified property. This method allows the server to provide custom information about the request for S e R V L e t. For example, Java Web Server has three available attributes: J a v a x. N e t. S L. C i p h e R S U I T E, J A V a. N e t. S L. P e e R _ c E R T I f i c A T E S and J A V A x. N e t. S s L. S E S I O n. The SE R v L e t running on the J a V AWEB Server can get these attributes connected to the client S s. 2.3.3 Transfer H T M L Information This section first explains how to return a standard HTML Response from S E R V L E T, then explain how to establish a client's persistent connection to reduce the overhead of returning R e S P O N s E. Finally, some additional things in handling HTML and HTTP, including the support class to objectify HTML output, return errors and other status code, send custom header information, redirect request, use customer traction, customer Line detection and write data to the server log. 1. Response structure HTTP servlet can return three information for customers: a status code, any number of H t t p-head and response information. The status code is an integer, as you think, it describes the status. The status code can indicate success and fail, or tell the client to take the next step to complete the requesting process.

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 (" Hello World! </ Title> "); Out.println (" </ Head> "); Out.Println (" <body> "); out.println (" <h1> Hello World! </ h1>); Out.Println ("</ Body>"); Out.println "</ html>");}} 5. Status code currently our example has not yet set the status code of the HTTP response. If SE R V L e t does not specify a status code, the server sets it to the default value 200 "O K" status code. This is very convenient when successfully returning a standard response. However, using the status code, S E R V L e t can do more work to the response information, for example, it can redirect requests and report errors. The most commonly used status code is defined in the H T T P S E R V L E T R E S P O N S E class being defined as a Public Final Static Int. Table 2 - 1 Lists a few of them, all of the status codes can be found in Chapter 6. Table 2-1 HTTP Status Code Help Reproduction Material Value Default Message Significance S C_ O K 2 0 0 O K Customer Request Success, the server's response information contains the requested data. This is the default status code S c _ N o _ C O N t e n 2 0 4 No Contentor's request is successful, but there is no new response body returns. The browser that receives this status code should retain the documentation views of their current R. When S e R V L e t collects data from the form, you want the browser to keep the form while avoiding the "D O c u m e n tcontains no data" error message, this status code is useful for the second chapter preparatory knowledge 47</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-3321.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="3321" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.028</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'uCc3FU58S_2FAqULg3tPBBONez1OLxtZvo58pUjxHVSvgwZ74UBj9KBi0H2JPwtsZzdkKgQniwqJw5W3GyeLT1Ug_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>