In-depth use of Jetty

Source: Internet
Author: User

Introduction:Jetty is a Java-based, open-source, standard-based HTTP server and Web Container with rich functions. It can be used for commercial behavior for free. The jetty project was established in 1995 and now has many successful products based on Jetty, such as Apache geromino, JBoss, IBM Tivoli, and Cisco sesm. Jetty can be used as a traditional Web server or dynamic content server, and jetty can be easily embedded into Java applications.Program.

Features

Ease of use

Ease of use is the basic principle of jetty design. ease of use is mainly reflected in the following aspects:

1. Configure jetty through XML or API;
2. The default configuration can meet most of the requirements;
3. Embed jetty into an application.Code;
Scalability

In applications that use Ajax Web 2.0, each connection needs to be maintained for a longer period of time, resulting in a sharp increase in thread and memory consumption. This causes us to worry that the performance of the entire program will be affected by the bottleneck of a single component. But with jetty:

1. Even with a large number of service requests, the system performance can be maintained in an acceptable state.
2. Use the continuation mechanism to process a large number of user requests and connections with a long time.
In addition, Jetty has designed very good interfaces. Therefore, when some jetty implementation cannot meet users' needs, users can easily modify some jetty implementations, this makes jetty suitable for special application needs.

Easy to embed

Jetty was designed as an excellent component at the beginning, which means jetty can be easily embedded into the application without the need for the program to make changes to use jetty. To some extent, you can also regard jetty as an embedded web server.

--------------------------------------------------------------------------------

Deploy applications

Deploying your own applications to Jetty is very simple. First, compress the developed applications into war packages and place them under the webapps directory of jetty. Run the following command to start the jetty server: Java-jar start. jar. We can access our application. jetty's default port is 8080, and the war name is the root context of our application. For example, a typical URL is http: // 127.0.0.1: 8080/sample/index. jsp.

--------------------------------------------------------------------------------

How to embed jetty into a program

It is very simple to embed jetty into a program, as shown in code 1: First, we create a server object, set the port to 8080, and then add a default handler for this server object. Then we set the server using the configuration file Jetty. xml. Finally, we can start the server using the method server. Start. From this code, we can see that Jetty is very suitable for embedding it into our applications as a component, which is also a very important feature of jetty.

Listing 1. code snippets

Copy code The Code is as follows: public class jettyserver {

Public static void main (string [] ARGs ){
Server = new server (8080 );
Server. sethandler (New defaulthandler ());
Xmlconfiguration configuration = NULL;
Try {
Configuration = new xmlconfiguration (
New fileinputstream ("C:/development/jetty/jetty-6.1.6rc0/etc/Jetty. xml "));
} Catch (filenotfoundexception E1 ){
E1.printstacktrace ();
} Catch (saxexception E1 ){
E1.printstacktrace ();
} Catch (ioexception E1 ){
E1.printstacktrace ();
}

Try {
Configuration. Configure (server );
Server. Start ();
} Catch (exception e ){
E. printstacktrace ();
}
}
}

Next we will analyze how the jetty server is started. First, we noticed that the server class actually inherits httpserver. When the jetty server is started, that is, if you enter Java-jar start in the command line under the jetty root directory. jar ETC/jetty. XML. Note that there is a configuration file jetty. XML as the running parameter, this parameter can also be other configuration files, can be multiple xml configuration files, in fact, this configuration file is like the struts-config.xml file when we use struts, write the components required to run the server. For example, the component classes required for the configuration of httpserver in the previous section can be written in this configuration file. When jetty server is started using the preceding method, the main method in the server class is called. This portal method first constructs a server class instance (in fact, an httpserver is constructed ), during instance creation, an object of the xmlconfiguration class will be constructed to read the parameter configuration file, and then the xmlconfiguration object generated by this configuration file will be used to configure the server, the configuration process uses the Java reflection mechanism to call the server method and input the parameters written in the configuration file to add httplistener, httpcontext, httphandler to the server, and web application (corresponding to our web application ).

--------------------------------------------------------------------------------

Jetty's continuation Mechanism

To discuss jetty's continuation mechanism, we should first mention Ajax technology, which is a very popular technology for developing web applications and an important part of Web 2.0. A core object in Ajax technology is the XMLHTTPRequest object, which supports asynchronous requests. The so-called asynchronous request means that when the client sends a request to the server, the client does not have to wait for the server to respond. In this way, the whole page will not be refreshed, providing a better user experience. When the server returns a response, the client uses a JavaScript function to process the returned value to update the values of some elements on the page. However, in many cases, this asynchronous event occurs only in a small part. How can we ensure that the client will know immediately after the server has a response, we have two ways to solve this problem. First, let the browser request the server every few seconds to obtain the change, which is called polling. Second, the server maintains a persistent connection with the browser to transmit data. The persistent connection technology is called comet.

It is easy to find that the main drawback of the polling method is that a large amount of transmission waste is generated. Most requests to the server may be invalid. That is to say, the events that the client waits for have not occurred. If there are a large number of clients, this kind of network transmission waste is very bad. Especially for applications that have been updated on the server for a long time, such as email programs, this waste is even greater. In addition, the server's ability to process requests also increases the requirements. If a request is sent to the server for a long time, the client cannot receive a timely response.

If you use the comet technology, the client and the server must maintain a persistent connection. Generally, each servlet on the server will exclusively occupy one thread, this will make the server have a lot of multithreading at the same time, which will also bring great challenges to the server's processing capability in the case of many clients.

Jetty uses Java's non-blocking I/O technology to process a large number of concurrent connections. Jetty has a mechanism for handling persistent connections: A feature called continuations. Using the continuation mechanism, Jetty enables a thread to simultaneously process multiple asynchronous requests sent from clients, next we will use the server-side code of a simplified chat program to demonstrate the difference between not using the continuation mechanism and using continuation.

Listing 2. Continuation Mechanism

Copy code The Code is as follows: public class chatcontinuation extends httpservlet {

Public void dopost (httpservletrequest request, httpservletresponse response ){
Postmessage (request, response );
}

Private void postmessage (httpservletrequest request, httpservletresponse response)
{
Httpsession session = request. getsession (true );
People = (people) Session. getattribute (session. GETID ());
If (! People. hasevent ())
{
Continuation continuation =
Continuationsupport. getcontinuation (request, this );
People. setcontinuation (continuation );
Continuation. Suspend (1000 );
}
People. setcontinuation (null );
People. sendevent (response );
}
}

We noticed that we first get a continuation object and then hold it for 1 second until it times out or is awakened by the Resume function in the middle. here we need to explain that after the suspend function is called, this thread can process other requests, which greatly improves the concurrency of the program and makes the persistent connection highly scalable.

If we do not use the continuation mechanism, the program is shown in listing 3:

Listing 3. Do not use the continuation Mechanism

Copy code The Code is as follows: public class chat extends httpservlet {
Public void dopost (httpservletrequest request, httpservletresponse response ){
Postmessage (request, response );
}

Private void postmessage (httpservletrequest request, httpservletresponse response)
{
Httpsession session = request. getsession (true );

People = (people) Session. getattribute (session. GETID ());

While (! People. hasevent ())
{
Try {
Thread. Sleep (1000 );
} Catch (interruptedexception e ){
E. printstacktrace ();
}
}
People. setcontinuation (null );
People. sendevent (response );
}
}

We noticed that the thread was suspended during the waiting time until the waiting event occurred. However, this thread cannot process other requests while waiting, this causes the server's processing capability to be unable to keep up when there are many clients. Next we will explain how jetty's continuation mechanism works.

To use continuatins, Jetty must be configured to use its selectchannelctor ctor to process requests. This connector Ctor is built on java. Nio API, allowing it to maintain each connection open without consuming one thread. When selectchannelconnector is used, continuationsupport. getcontinuation () provides a selectchannelconnector. retrycontinuation instance (however, you must program the continuation interface ). When suspend () is called on retrycontinuation, it throws a special runtime exception-retryrequest, Which is propagated outside the servlet and traced back to the filter chain and finally captured by selectchannelconnector. However, no exception response is sent to the client, but the request is kept in the pending continuations queue, and the HTTP connection is kept open. In this way, the thread used to serve the request is returned to threadpool, and then can be used to serve other requests. The paused request stays in the pending continuations queue until the specified expiration time, or calls the resume () method on its continuation. When any condition is triggered, the request is resubmitted to the servlet (through the filter chain ). In this way, the entire request is "replayed" until the retryrequest exception is not thrown, and then the execution continues as normal.

--------------------------------------------------------------------------------

Jetty Security

To prevent anyone from having the permission to shut down an enabled jetty server, we can specify parameters when starting the jetty server so that the user must provide a password to shut down the jetty server, the command to start the jetty server is as follows:

Copy code The Code is as follows: Java-dstop. Port = 8079-dstop. Key = mypassword-jar start. Jar

In this way, the user must provide the password "mypassword" When stopping the jetty server ".

--------------------------------------------------------------------------------

Summary

Jetty is a very easy-to-use Web server. It is very small and can be easily embedded into our applications. In addition, it is specially optimized for Ajax technology of Web 2.0, this also enables our Ajax applications to have better performance.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.