Servlet
Tutorial
One,
Servlet
Introduction
Servlet is a general expansion of servers that support Java. Its most common use is to extend the web server, providing very safe, portable, easy-to-use CGI alternatives. It is a dynamically loaded module that serves as a request from a web server. It is fully running on the Java virtual machine. Because it runs on the server, it does not rely on the browser compatibility.
Servlet container:
Responsible for handling the customer request, transmitting the request to the servlet and returns the result to the customer. The actual implementation of the container of different programs may vary, but the interface between the container and the servlet is defined by the Servlet API. This interface defines the method of the servlet container to be called on the servlet and passed to the SERVLET class.
SERVLET lifecycle:
1, a instance of the servlet container creates a servlet
2, the container calls the init () method of this instance
3. If the container has a request to the servlet, the service () method of this instance is called.
4, the container is destroying the destroy () method before the present example
5, destroy and mark this example for garbage collection
Once a servlet is requested, there is no way to prevent the container from performing a complete lifecycle.
The container creates an instance of it when servlet is called, and keeps this instance in memory, allowing it to process all requests. The container can decide to remove this instance from memory at any time. In a typical model, the container creates a separate instance for each servlet, and the container does not create a new thread per recesered request, but uses a thread pool to dynamically assign the thread to arrival, but This is the same as the SERVLET's point of view, the effect and the effect of creating a new thread for each request.
Servlet API
Servlet interface:
Public interface servlet
Its life cycle is defined by the javax.servlet.servlet interface. This interface must be implemented directly or indirect when you write servlet. Generally tended to indirectly: derived from javax.servlet.GenericServlet or javax.servlet.http.httpservlet. Five methods must be implemented when implementing a servlet interface:
INIT ():
Public Void Init (ServletConfig Config) Throws ServleTexception
Once instantiated the servlet, the container calls this method. The container contains a servletconfig object to this method so that the instance of the servlet can save the configuration data related to the container for later use. If this method does not end properly, you will throw a servletException. Once the exception is thrown, the servlet is no longer executed, and the call to it will cause the container to reload and run this method again. The interface specifies any servlet instance, this method can only be called once, before any request is passed to the servlet, this method can run without throwing an abnormally.
Service ():
Public Void Service (ServletRequest Req, ServletResponse Res) THROWS ServleTexception, IOEXCEPTION
This method can only be called to process user requests only after successful initialization. The previous parameter provides methods and fields that access the initial request data, and the latter method provides a method of constructing a servlet constructor.
DESTROY ():
Public void destroy ()
The container can terminate the servlet service at any time. The container is called before this method must be completed to the service () thread sufficient time, so the interface specifies that the design when Service () is executing is not executed.
GetServletConfig ():
Public servletconfig getServletConfig () When servlet is initialized, the container passes a servletconfig object and saved in a servlet instance, which allows access to both content: Initializing parameters and servletContext objects, the former is usually specified by the container in the file, allowed at runtime Pass the scheduling information to the sevrlet, the latter provides information about the container for servlets. This method allows servlet to get this object and configuration information at any time.
GetServletInfo ():
Public String GetServletInfo ()
This method returns a String object that contains information of servlet, such as developers, creation dates, description information, and more. This method can also be used in the container.
GenericServlet class
Public Abstract Class GenericServlet Implants Servlet, ServletConfig, Serializable
Such a basic implementation part of the servlet interface is provided, and its service () method is declared as Abstract, so it is necessary to be derived. Init (servletConfig conf) method stores the servletconfig object in a private transient instance variable, the getServletConfig () method returns a pointer to this object, if you overload this method, you will not use GetServletConfig to get a servletconfig object, if Really want to overload, remember to include the call to super.config. The version 2.1 API provides an overloaded INIT () method. Now there is a call to init () at the end of the init (servletConfig) method, although it is empty. The version of the version of the version of the API, this class implements the servletconfig interface, which makes the developer to directly call servletconfig in the case of servletconfig objects, these methods are: GetInitParameter (), GetInitParameterNames (), GetServletContext. Such a method of writing two write logs, which actually calls the corresponding method on servletContext. Log (String MSG) Method Write the servlet's name and MSG parameters to the log of the container, and the log (String MSG, Throwable Cause) includes an exception in addition to the servlet.
HTTPSERVLET class
This class extends the GenericServlet class and provides a more relevant implementation with HTTP interfaces for the servlet interface.
Service ():
Protected Void Service (httpservletRequest Req, httpservletResponse res) throws servletexception, ioException
Public Void Service (httpservletRequest Req, httpservletResponse res) throws servletexception, ioException
This method is a distributor of an HTTP request, which cannot be overloaded at any time. When the request arrives, the service () method determines the type of request (GET, POST, HEAD, OPTIONS, DELETE, PUT, TRACE), and distribute the request to the corresponding processing method (doget (), dopost (), dohead () DOOPTIONS (), Dodelete (), doput (), dotrace ()) Each DO method has the same form as the first service (). In response to a specific type of HTTP request, we must overrun the corresponding DO method. If the servlet receives an HTTP request and you do not overload the corresponding DO method, it returns a standard HTTP error that this method is not available to this resource. getlatModified ():
Protected long getlastmodified (httpservletRequest Req)
The method returns from the Time-dependent time-dependent time to modify the servlet from 0:0:05 0:00 January 1, 1970, 1970, and the default is to return a negative representation time unknown. When processing a GET request, call this method to know the recent modification time of the servlet, the server can decide whether the result is removed from the cache.
HTTPSERVLETREQUEST interface
Public Interface HttpservletRequest Extends ServletRequest
All objects that implement this interface (such as HTTP request objects passed from the servlet container) allow servlets to access all requests through their own methods. Below is some basic methods used to obtain form data.
GetParameter ()
Public String getParameter (String Key)
This method attempts to place the corresponding parameters according to the keyword in the query string and return its value. If there are multiple values, return the first value in the list. Returns NULL if you do not specify a parameter in the request information.
getParameterValues ():
Public string [] getParameterValers (String Key)
If a parameter can return multiple values, such as checkbox, you can use this method to get all values of the corresponding parameters. Returns NULL if you do not specify a parameter in the request information.
GetParameterNames ():
Public Enumeration getParameterNames ()
This method returns an ENUMERATION object that contains all the parameter names of the corresponding request.
HTTPSERVLETRESPONSE interface
Public Interface HttpservletResponse Extends ServletResponse
The servlet container provides an object that implements the interface and passes it to the servlet through the service () method. Through this object and its method, the servlet can modify the head and return the result.
setContentType ():
Public void setContentType (String Type)
This method must be used to set the MIME type of HTTP response before sending a response to the caller. Can be any effective MIME type, when returning to the browser is the "Text / HTML" type.
GetWriter ():
Public PrintWriter getWriter () THROWS IOEXCEPTION
This method returns the PrintWriter object and returns the result of the servlet as a text to the caller. The PrintWriter object automatically converts the Unicode coded characters within Java into correct encoding to enable the client to read.
getOutputStream ():
Public servletOutputStream GetputStream () THROWS IOException
This method returns a ServletOutputStream object, which is a subclass of java.io.outputstream. This object sends binary data to the customer. setHeader ():
Public void setheader (String name, string value)
This method is used to set the HTTP response header to the customer. There are some shortcuts to change some common response heads, but sometimes they need to call this method directly.
Compilation conditions
Need a copy of JSDK from http://java.sun.com/products/servlet/ and moves servlet.jar to the / jre / lib / ext directory in the JDK installation directory. If it is JDK1.1, move it under / lib and add servlet.jar to the ClassPath.
Operating conditions
Servlet server-side programs such as Apache Jserv, Jrun Server, WebLogic, WebSphere, Tomcat, Resin are required.
Simple example
Import java.io. *;
Import javax.servlet. *;
Import javax.servlet.http. *;
public
Class HelloWorld
Extends httpservlet {
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 ("
Out.println (" HEAD>");
Out.println ("
Out.println ("
Out.println (" Body>");
Out.println (" html>");
}
}
Servlet performance and efficiency
A servlet is only initialized once, so minimal inefficiency will also have a lot of impact over time. In the code, you need to consider the use of String objects. If you generate an HTML response requires a lot of strings, you should not generate a String object for each string because it produces a lot of String and StringBuffer objects, resulting in a lot of object constructs. Consumption and garbage collection burden, the solution is to write all the way to write all the needs to write directly, or create a StringBuffer object, and use the Append () method to add text.
Timely return
Sometimes, the program takes a long time to execute. In this case, it should be sent to the client some information, not a white screen for a long time, which can send some things to a certain extent, you can use PrintWriter's flush () Method Force existing content back to the browser.
Servlet session
Since the protocol HTTP used by the web server is a stateless protocol, you need to maintain a series of requests for a series of requests to use other additional means, in the previous, the general method is to use: l Hidden Table field: In the browser, this type of field is invisible, however, it is transmitted in the request, and the server-side program can read its value. Its advantage is that it is easy, and most browser supports; the disadvantage is that the field must be established in a specific order, the client can get its value by viewing the source code, click the "Back" button in the browser to lose to the current The additional fields in the page also limits the generation of the user's dynamic generation document.
l cookie: It is some key data dishes, which is created by the server and stored by the client's browser. The browser maintains its own cookie table, which makes it as a session tracking solution. The benefit of using cookies is that it is more intuitive than storing data in the URL or form. Its disadvantage is that it can be used to track users longer than a short session, and can even be used to track each request sent by a user to the site, so some people are worried about their privacy issues and close cookie, some old The browser does not support cookies. Servlet API provides a cookie class to support cookies, add and read cookies with httpservletresponse.addcookie () and httpservletresponse.getCookies () methods.
l URL rewrite: Modify the requested URL to contain the session ID. The disadvantage of this method is that for a large amount of data, the URL will become very long and the control; in some environments, the string length of the URL has a certain limit; the data confidential issue, you may not want the side of the side or You can use the same computer to see your session data. Servlet provides an HTTPSERVLETREQUEST class to get parameters.
The Servlet API has its own built-in session tracking, which can be used with HTTPSession objects. Its setAttribute () method binds a pair of name / value data, save it to the current session, if the name already exists in the session, the syntax is: public void setttribute (String Name, Object Value). The GetAttribute () method reads the object stored in the session, the syntax is: Public Object GetAttribute (String Name). GetAttributeNames () method Returns all the names stored in the session, the syntax is: public string [] GetAttributeNames (). The last method is the removettribute () method, which deletes the specified information from the session, and the syntax is: Public Void Removeattribute (String Name). The HttpSession object can be obtained using the HTTPServletRequest object Request's GetSession (TRUE) method. The parameter is true means that if there is no such object, one is created.
two,
servlet
Specification definition
Servlet
life cycle
The servlet has a good definition of survival, including how to load, instantiate, initialize, process client requests, and how to remove it. This survival period is expressed by the init, service, and destroy method of the javax.servlet.servlet interface.
1, loading and instantiation
The container is responsible for loading and instantiation a servlet. Instantiation and loading can occur when the engine is started, or it may be postponed to the container to request the servlet to request a service to request a service.
First, the container must first position the servlet class. In the case of necessary, the container uses the usual Java class load tool to load the servlet, which may be from the native file system, or from remote file system or even other network services. After the container loads the servlet class, it instantiates an instance of the class. It should be noted that multiple instances may be instantiated, such as a servlet class with multiple definitions because there are different initial parameters, or the servlet implements SingLethReadModel to generate an instance pool for the container. 2, initialization
After servlet is loaded and instantiated, the container must initialize it before it can handle the client request. The process of initialization is mainly to read permanent configuration information, expensive resources (such as JDBC connections), and other tasks that only need to perform once. By calling its init method and delivering a unique one (each servlet definition one) ServletConfig object completes this process. This configuration object to which it passes allows the servlet to access the name-value of Name-Value in the configuration information of the container. This configuration object simultaneously provides a method of accessing a specific object that implements a ServletContext interface, which describes the running environment of the servlet.
2.1 Initialization error handling
During initialization, the servlet instance may not be able to perform valid services by throwing unavailableException or servleTexception exceptions. If a servlet throws a such anomaly, it will not be placed into a valid service and should be released immediately by the container. In this case, the Destroy method will not be called because initialization is not completed successfully. After the failed instance is released, the container may instantiate a new instance at any time, and the unique exception to this rule is that the exception thrown by the failed servlet is UnavailableException and the exception pointed out the minimum invalid time, then the container is At least the time limit indicated at this time will re-try the creation of a new instance.
2.2, tool factors
When the tool (Note: According to the author's understanding, this tool may be some inspection tools of the application server, usually the legality and integrity of the application, it may load and internal, "INTROSPECT) The class in this application will trigger a static initial method of those classes to be executed. Therefore, the developer cannot assume that it is only the active container runtime after the servlet's init method is called. As an example, this means that the servlet does not attempt to establish a database connection or connect the EJB container when it is called when it is called.
3. Processing request
After the servlet is initialized, the container can use it to deal with the request. Each request is represented by an object of the servletRequest type, while servlet uses servletResponse back to request. These objects are passed to the servlet as parameters of the service method. In the case of an HTTP request, the container must provide the specific implementation of HTTPServletRequest and HttpservletResponse, representing the request and response. It should be noted that the container may create a servlet instance and put it into the state of the waiting service, but this instance may not process any request at all in its living life.
3.1, multi-threaded problem
The container may simultaneously send a request for multiple clients to a instance of the service method, which means that developers must ensure that the written servlet can handle concurrency issues. If the developer wants to prevent this default behavior, then he can let him write the servlet to achieve SingleThreadModel. Implementing this class ensures that only one thread will only be executed in the execution of the service method and execute at once. The container can satisfy this by queuing or maintaining a servlet instance pool. If servlet is part of a distributed application, then the container may maintain an instance pool in each JVM of the application distribution. If the developer uses the Synchronized keyword to define the service method (or doget and dopost), the container will queue the request, which is required by the underlying Java runtime system. We strongly recommend developers not to synchronize the service method such as Doget and Dopost such as Doget and Dopost. 3.2, abnormalities in the request
Servlet is likely to throw servleTexception or unavailableException when serving the request. ServletException indicates that an error container should use the appropriate method to clear the request during the process of processing requests. UNAVAILABLEEXCEPTION indicates that the servlet cannot process the request, which may be temporary, or may be permanent. If UNAVAILABLEEXCEPTION indicates permanent, the container must remove the servlet from the service, call its Destroy method and release its instance. If it is indicated temporary, the container can choose to send any requests to it in this temporary unacceptable time period indicated in exception information. The request to be rejected in this time period must use the service_unavailable (503) return status to respond and should carry the response header of the retry-after indicating that it is only temporary. The container can also choose whether or permanent and removal of a servlet without the distinction of temporary and permanent unavailability.
3.3 Thread safety
Developers should pay attention to the request and response objects implemented by the container (Note: HTTPSERVLETREQUEST and HTTPSERVLETREQUEST and HTTPSERVLETREQUEST and HTTPSERVLETRESPONESE) that the container implementation is not guaranteed, which means they can only be used within the range of requesting processing threads, these objects cannot be Being cited by other execution threads because the behavior of reference is uncertain.
4, the service end
The container is not required to save a loaded servlet how long, so a servlet instance may only survive in the container for a few milliseconds, of course, may be other longer times (but will definitely short over the container)
When the container decides to remove (whose reason may be saved) or it is turned off), it must allow the servlet to release any resources it is using and save any permanent state (this process is reached by calling the Destroy method). The container must allow threads that are executing in the service method before being able to call the Destroy method or before the server definition (this time period is previously called DESTROY). Once the DESTROY method is called, the container will not send any request to the instance. If the container needs to use the servlet, it must create a new instance. After the DESTROY method is complete, the container must release the servlet instance so that it can be recycled by garbage.
three,
Servervet
Why only need to be implemented?
doget
with
Dopost
The Server Vent interface only defines a service method is Service, and the HTTPSERVLET class implements the method and requires one of the following methods:
Doget: Processing GET Request
Dopost: Processing POST Request
DOPUT: Handling PUT Request Dodelete: Processing Delete Request
DoHead: Handling HEAD Request
DOOPTIONS: Handling Options Request
Dotrace: Processing Trace Request
Typically, when developing HTTP-based servlets, developers only need to care about doget and dopost methods, and other methods require developers very familiar with HTTP programming, so these methods are considered to be advanced methods.
And usually, we implemented servlets are extended from httpservlets.
DOPUT and Dodelete methods allow developers to support the corresponding features of HTTP / 1.1;
DoHead is a way that has been implemented, which will perform DOGET but return to the client to return to the header of the header to the client;
The DoOptions method automatically returns the HTTP method information directly supported by the servlet;
Dotrace method Returns all header information in the Trace request.
For those containers that only support HTTP / 1.0, only doget, dohead, and dopost methods are used because the HTTP / 1.0 protocol does not define PUT, DELETE, OPTIONS, or Trace request.
In addition, the HTTPServlet defines the GetLastModified method to support Condition GET operations. Conditional GET Operation refers to the use of GET to request resources and specifying the server only if the server is modified after the resource content is modified after the specified time is modified. For those servlets that implement the DOGET method and content between different requests, it should implement this method to improve the utilization of network resources.
In addition, it is to mention that the servlet container must implement the HTTP / 1.0 protocol specification in accordance with the requirements of the specification. It is recommended to implement the HTTP / 1.1 specification. On this basis, other protocols based on the Based Request Response Model can be implemented. (Eg, HTTPS).
four,
servlet
The number of instances and therefore caused problems
By default, only a servlet class instance is generated for each servlet definition. In the case of a servlet implementation of the SingLethReadModel interface, the container can generate multiple instances to cope with heavy requests, or send the request to queue to the same instance (for a high-performance container, it may be the combination of these two ways, because The number of instances is limited, so a plurality of instances in the thread security mode will wait for a plurality of instances in the container to serve the request. For servlets developed for DISTRIBUTABLE, there is an instance of each servlet definition in each JVM. If the servlet is also implemented in such applications, the SingLethReadModel interface is implemented, then each JVM A servlet definition may also have multiple instances.
Using the SingLethReadModel interface, you can guarantee a service method for a thread to perform a given instance, you need to note that this guarantee can only be applied to the servlet instance, those that can be accessed by multiple servlet instances (such as httpsession instances) still have multiple Servlet is valid, even if they achieve SingleThreadModel.
According to these instructions in the specification, we need to consider multithreading problems when implementing our own Serverve. In general, do not define variable members in the servlet, can only define some constants (use final definitions, if not used, should Note that the value should not be modified in the program), the author has seen a defined servlet: public class somehttpservlet extends httpservlet {
HttpSession session;
...
}
Such servlets will have problems in use. All users will share a session (this is a system resource, isn't it ?: :)), so the information requested by the user suddenly ran to another user's IE window Happiness .
Moreover, even if your servlet implements the SingLethReadModel interface, it is not necessary to define a variable member because the member's information will remain, and this is meaningless to other users. (You are sure that there is a meaningful case, such as some count)
It is also necessary to explain that the above description is for the servlet definition, while the servlet definition does not equivalent the servlet class definition, ie a servlet class may have multiple servlet definitions, but the author has not found "servlet definition" Definitions, specification that may have different initial parameters when instantifying a servlet, but this is different from multiple constructors with parameters. In general, we can think that a servlet class corresponds to a servlet definition.
Fives,
servlet
Session
The HTTP protocol is a stateless protocol, and we often need to record a series of requests from a particular client for the current Web application. There are already many technologies that have a lot of session tracking, but it is not very convenient to use for programmers. The Servlet specification defines a simple HttpSession interface to facilitate session tracking of the Servlet container without requiring the details of the developer to pay attention to the implementation.
In general, there are two most common session tracking mechanisms, one is the URL rewrite. Use URL rewrite to perform session tracking with the client's access. URL rewriting includes data that can be interpreted to the URL path to add some containers. Specifications require that the session ID must be encoded in the URL path, the parameter name must be jsessionID, for example:
http://www.myserver.com/catalog/index.html;jsessionID=1234
The other is the most common cookie now, and the specification requires all servlets to support cookies. The container sends a cookie to the client, and the client returns the cookie to the server in the request in the same session. The name of the session tracking cookie must be jsessionID.
A new session function is an SSL session. SSL (Secure Sockets Layer, Security Sockets) is an encryption technology used by HTTPS protocol, built-in session tracking, and servlet containers can be very easy to use. Session tracking. (But HTTPS is not a protocol that the specification requires servlets must support)
Because HTTP is a protocol based on request response, the session is only newly established after the client is added. A session is added when the session tracking information is successfully returned to the server to indicate the session to establish a session. If the client does not join a session, the next request will not be considered part of the session. How to do not know the session or the client selection does not join a session, then the session is considered new. Developers must design their own session processing status in their application, where there is no join session, where you can't join the session and where you don't need to join the session. Specifications require httpsession that is valid at the application or servlet context, such as cookie, the underlying mechanism of the creation session, can be shared in the context, but for those exposed objects, and more importantly those attributes of objects cannot be shared in context.
For the binding of the properties of the session, any object can be bound to a naming property. The bound property object is also visible for other servlets in the same servletContext and in the same session processing.
Some objects require notification when they are being added sessions or being removed from the session, such information can be obtained by making the object implementation HttpSessionBindingListener interface. This interface defines that two methods are used to mark the bind to sessions or remove from the session.
The valuebound method is called before the object passes through GetAttribute, and the valueunbound method can not be called after the object is not available through GetAttribute.
Since HTTP is a stateless protocol, there is no obvious signal when the client is no longer active, which means that only one mechanism can be used to indicate that the client is no longer active: timeout. The default time limit for the session is defined by the servlet container and can be obtained by getMaxInactiveInterVal through httpsession. Developers can also set up using the SetMaxInactiveInterval method. These methods returned by seconds. If the time limit is set to -1, then it means never It will time out.
By calling the HTTPSession GetLastAccessedTime method, we can get access times before the current request. The session is considered to be accessed when a request is processed by the servlet context.
It is also necessary to pay attention to some of the semantic issues of a very important session.
Multithreaded Problem: Multiple request threads may access the same session at the same time, developers' responsibility to synchronize resources in the access session in an appropriate manner.
Distributed Environment: For applications marked as available, all requests in the same session can only be processed by a single VM. At the same time, all objects placed in httpsession must implement the serializable interface, otherwise the container may throw IllegalarGumentException (there is no throwing in jboss_tomcat, but if there is an unfinished session when closing the server, then the server is trying to store The serialization exception occurs when the session is restarted, and there will be abnormalities when restarting. This limitation means that developers do not encounter them in a non-distributable container. In addition, the container provider ensures scalability by moving a session object and its content from one active node of the distributed system to other different nodes of the system.
The semantics of the client: Based on the cookie or SSL certificate is usually controlled by the web browser and does not contact the specific browser window, the request from all windows from the client application may be the same session. In order to achieve maximum portability, developers cannot always assume that requests for all windows of a particular client are in the same session.
six,
Bean
with
Servlet
Enterprise application
J2EE is an enterprise application development platform, including support for EJB, Servlet, JavaServer Page, JNDI, XML, etc. Enterprise applications for thin client multilayer architectures can be developed on this platform. Enterprise JavaBean technology is the main foundation of J2EE. EJB technology provides a scalable frame structure for performing application logic in a distributed computing environment. J2EE solves seamless binding to develop and configure server applications on the Java platform by combining EJB components structures and other enterprise technologies.
To develop your business apps using J2EE, you have to install a web server on your machine, but also support XML. In order to run the Java 2 API in the browser, you have to install a plugin that supports Java2 in your browser.
Here, how to write a business application with a simple thin client including HTML pages, servlet, and session beans with J2EE SDK. Is it sounded? Let's start below.
It is also to remind a little thing: when programming, the appropriate increase in Catch clause is a good programming style. If the example code throws a correct exception, the code is surrounded by the program structure like Try / Catch. The Catch clause should be added to the process of processing an exception, do not leave a blank. At least, you should add statements: E.PrintStackTrace () to display exception information at the console.
J2EE SDK is a non-commercial stuff for demonstration, education, etc. on a J2EE platform. You can download from JavaSoft's website. It is very suitable for learning. If you don't go abroad, you can also download from the FTP server of our universities, fast speed, but may not be the latest.
Example of the application of thin client multilayer architecture:
This example invokes a servlet, servlet with Java's Name Directory Services Interface (JNDI) APIs to find a session session bean to perform a calculation. When the servlet gets the result of the calculation, the servlet returns the calculation result to the user of the HTML page.
The reason this is a thin client application because the servlet itself does not perform any application logic. This simple calculation is performed by a session bean on the J2EE application server. Customers do not have any operations of the process, all calculations are done by the session bean.
The so-called multilayer system is actually consisting of three or four layers. Our example is actually a structure of four layers. The three-layer architecture is based on the standard two-layer client / server structure, adds a multi-threaded application server to the non-visible client and the background database. The four-layer architecture is replaced by the client's application by the browser and HTML pages via Servlet and JavaServer Pages technology. This example we temporarily use three layers in the next example. Let's visit the database. In this way, it is extended to four layers. After another, we will involve JavaServer Pages technology and XML technology.
J2EE software installation:
In order to make our examples to run, you must first download a version of 1.2.1 of Java2 SDK Enterprise Edition (J2EE) and a version of J2SE (Java 2 Standard Edition). In the Windows 2000 system, suppose we put J2EE and J2SE to the C: / J2EE directory. The detailed directory is as follows:
J2EE: C: /J2EE/J2SDKEE1.2.1
J2SE: C: /J2EE/JDK1.2.2
Setting: Path and ClassPath:
The downloaded thing includes J2EE's application servers, Cloudscape databases, using the web server, development and configuration of the encryption socket protocol layer, the enterprise-class Java APIS. Its Path and ClassPath are set as follows: PATH setting: In the Windows system, you need to contain the following two directories:
C: /j2ee/j2sdkee1.2.1/bin
C: /j2ee/jdk1.2.2/bin
ClassPath setting: In the Windows system, you need to contain the ClassPath parameter below the file:
C: /J2ee/j2sdkee.1.2.1/lib/j2ee.jar
In addition, you have to configure environment variables:
J2EE_HOME = C: /J2EE/J2SDKEE1.2.1
Java_Home = C: /J2EE/JDK1.2.2
This way, you can perform the batch command below the C: /J2EE /J2SDKEE1.2.1/bin directory. Take a closer look at the batch of batch, you will find a lot of things.
J2EE application components:
J2EE programmers write J2EE components. The J2EE component is a fully fully equipped software unit. Pack other application components into J2EE applications and interfaces. The following application components are defined in the J2EE specification:
Application Customer Component
Enterprise JavaBean Components
Servlet and JavaServer Pages Components (also called web components)
Applet
In this example, we created a J2EE application and two J2EE components: a servlet and a session bean. Servlet and HTML files are bundled in a WAR (Web Archive) file. The class and interface of the session bean are bundled in a JAR file. Then add the WAR file and JAR file to the J2EE application, bundle into an EAR (Enterprise Archive) file. And verify the configuration of the test product environment.
In all the steps. In fact, many of the functions of many unused characters are implemented. Write session beans and servlets are development work. To create a J2EE application, assemble the J2EE component into the application is the assembly of the application. In fact, these work can be done in different places.
Create an HTML page:
This page name is Bonus.html. The HTML code is as follows:
In the code, it is interested in calling BonusServlet.class with alias. Because when the app is assembled later, it maps it to this alias BonusServlet.
Bonus Calculation h3>