Introduction to the Jetty project

jetty is an open source, standards-based, fully functional Java server. It is released under the Apache 2.0 license, so it is free for commercial use and distribution. First created in 1995, Jetty benefits from a broad user community, with a stable core developer for continued monograph development. There are many running examples of using Jetty, and this is just 10 out of 1000 instances of Jetty. Although Jetty's goals are low-key, countless sites and products use Jetty, but Jetty is everywhere!
Jetty can be used to:
◆ A traditional web server for static and dynamic web pages;
◆ Mostly a dedicated HTTP server backend for dynamic processing Web pages, just like Apache use mod_proxy;
◆ as an embedded component of a JAVA application.
This flexibility means that Jetty can be used in a variety of situations:
◆As an outer box with products, such as Tapestry, Liferay;
◆In the CD-ROM with the book, used to run examples;
◆Incorporated into programs to provide HTTP transport, such as JXTA, MX4J;
◆Integrated into JavaEE server as a web container, such as JOnAS, Geronimo, JBoss, JFox;
◆As a component of an application, such as Continuum, FishEye, Maven.
Characteristics of Jetty:
Simple
Jetty's guiding principle is "simple not complicated". Jetty is easy to understand and use:
◆Configure through API or XML file;
◆XML file syntax directly maps API operations on POJOs;
◆Default configuration file can make Jetty out-of-the-box;
◆ Only a small number of lines can embed a Jetty instance.

Scalability
In asynchronous Web 2.0-type applications using technologies such as AJAX, where connections stay longer than processing a static page, thread and memory requirements can grow dramatically.
The bottom layer has to handle these issues gracefully, a slow database connection can crash the site because the threads are full. Using Jetty...

◆Low performance loss under high-intensity service pressure;
◆Under the framework of existing web specifications, it can handle large user loads and ensure the continuity of long-term sessions;
◆Integrate existing clusters, such as WADI and Terracotta

Efficient A
lot of effort goes into optimizing the code, refining the code so that there are as few bugs as possible:
◆As few dependencies as possible;
◆Core is kept to a minimum, additional functions are placed in optional packages;
◆Scalability is a key issue;
◆The performance decays gently under high strength.

Embedded
Jetty is a very nice component. This means that it is easy to embed into an application without requiring the application to adapt to it:
◆Control patterns using dependency injection and

inversion
Pluggability Jetty is built to fit
Jetty's built-in pluggability. Implementations of all Jetty core components allow different choices, at least one or more, the implementation of the component will always provide. If these still can not meet your requirements, you are free to write low-level interfaces and abstract classes as the most basic. This means that Jetty can easily be used in a specific application environment. This is useful when Jetty is used as a web container in a JavaEE server, and Jetty's pluggability ensures a tight integration with the host container.



Reprinted from: http://shenpipi.spaces.live.com/Blog/cns!D36B637A9359DDC2!174.entry

What is Jetty?
A recently translated article
Abstract :
Jetty is an open source servlet container for Java-based web Content such as JSPs and servlets provide the runtime environment. Jetty is written in the Java language, and its API is distributed as a set of JAR packages. Developers can instantiate the Jetty container as an object that can quickly provide network and web connectivity for some stand-alone Java applications.
Toolkit

Jetty is an open source servlet container that provides a runtime environment for Java-based web content such as JSPs and servlets. Jetty is written in the Java language, and its API is distributed as a set of JAR packages. Developers can instantiate the Jetty container as an object that can quickly provide network and web connectivity for some stand-alone Java applications.

This article covers the following:
1. What's the point of an embedded servlet container?
2. Building an embedded container: Using The Jetty API
3. Separating configuration from code: XML-driven configuration files
4. Executable JAR packages
5. Conclusion
6. Resources

If someone were to name an open source servlet container, probably they would answer Apache Tomcat. However, Tomcat is not alone, we also have Jetty. Jetty as an optional servlet container is just an extra feature, and it's really famous because it was designed as a servlet container that can be embedded into other Java code. That said, the development team provides Jetty as a set of Jar files, so you can instantiate the servlet container as an object in your own code and manipulate the container object.

Jetty is not a new face in servlet containers; it has been around since 1998. Jetty is released under the Apache 2.0 open source license, and you can use Jetty in free and commercial software without paying royalties.

In this article, I'll give you some insight into why you need an embedded servlet container, explain the basics of the Jetty API, and show how to use XML configuration files to minimize Jetty code.

The sample code in this article was tested under Jetty 5.1.10 and Sun JDK 1.5.0_03.

Please keep the following author information and links when reprinting
Author : Ethan McCallum; shenpipi
Original: http://www.onjava.com/pub/a/onjava/2006/06/14/what-is-jetty.html
Matrix: http ://www.matrix.org.cn/resource/article/44/44588_Jetty.htmlKeyword
: What is the significance of Jetty

embedded servlet container?

Before you adopt Jetty, it is sensible to first ask yourself why you need to embed a servlet container in your application. What caught my eye was Jetty's ability to provide servlet functionality to an already existing application. This capability is useful to many organizations, including Java EE application server producers, software testers, and custom software producers. Most Java developers can be divided into these three situations.

First, consider the edge case of building your own Java EE application server. According to the specification, a complete application server must provide servlets, EJBs, and some other functions. You should take an existing and tested component and use Jetty instead of starting from scratch. Project groups such as Apache Geronimo, JBoss, and ObjectWeb JOnAS do the same when building their own Java EE application servers.

Software testers benefit from generating their own servlet containers on demand when existing containers are not sufficient. For example, a colleague once wanted to find some way to drive unit tests he wrote for web service code. For his situation - a few developers plus a few automated unit tests running in Cruise Control - I showed him how to dynamically (on the) his unit test suites fly) uses Jetty to instantiate a servlet container. No extra scripts, no leftover files, just code.

For those developing Java EE applications as products, why only provide a WAR file? In this way, you will have a headache for the specification of the container, and it will also increase the cost of your technical support. Instead, provide the customer with an application that has its own start, stop, and management functions. Even hardware manufacturers benefit: Jetty requires only 350k of memory for normal HTTP services (no servlets), which makes it possible to use it in smart devices. You can provide a web-based control panel with all the functionality of a Java web application without the stress of separate containers.

In the end, I'd wager that the most interesting use of embedded servlet containers happens to people who have never written traditional web-based applications. The combination of Java EE and HTTP can be used as the backend of a C/S structured program. Consider an event-driven service, such as the (hypothetical) Message-Driven Bank (mentioned in another article on onjava), started from the main() method and waiting for incoming requests, just like a daemon program in Unix. It's only a matter of time before some people will want to expose this program to a user-based style, such as a GUI desktop application.

To create your own base components, the protocol and socket communication code is the most annoying and distracting from the business logic, not to mention the things you might have to debug in the future. Using an embedded Jetty container to expose business logic over HTTP is a good option without making too many changes to existing programs. Choose to use GUIs such as Swing, SWT, XUI and wrap requests into HTTP Post operations, REST, or even SOAP to complete the loop. These general-purpose protocols may perform slightly worse than custom domain-specific protocols, but it won't take long for you to benefit from these already-existing tried-and-true protocols and save a lot of effort.

Building an Embedded Container: Using the Jetty API

Hope the above ideas will stimulate your appetite and give you a try with the embedded servlet container. The sample program Step1Driver demonstrates a simple Jetty-based service. It creates an instance of the servlet container, maps a servlet class to a URI, and invokes the servlet with some URL. I sacrifice some code quality for code brevity.

The Service object is the Jetty container, and a container is created by instantiating such an object.

Server service = new Server() ;



In this way, the Service object is like a hotel without doors: no one can enter and use it, so it is still useless. The next line of code sets the container to listen on localhost, port 7501.

service.addListener( "localhost:7501" ) ;



To listen on all interfaces, do not use the hostname ("addListener( ":7501" )"). As the name implies, you can call addListener() multiple times to listen on multiple interfaces.

Note that the sample code maintains a reference to the Server object, which is needed to stop the container in the future.
Mapping a web application to a Service is straightforward:

service.addWebApplication(
   "/someContextPath" ,
   "/path/to/some.war"
) ;



This call will process the web.xml deployment descriptor (descriptor) in a web application to map the filter servlets and servlets in it, just like other containers do. The first parameter is the context path, and all servlets and JSPs of this web application will be mapped to URIs relative to this path. The second parameter is the web application itself. Can be a packaged WAR file or a web application in directory format. Calling addWebApplication() again can be used to add other web applications.

Note that Jetty does not require a full compliant WAR file to deploy the servlet. If you write a custom application protocol on top of the HTTP protocol, you can load a single servlet and serve it over the network. There is no need to use a WAR file just to make a non-web application accessible via HTTP.

To map this one-off servlet, a context is dynamically created by calling getContext() on the Service object. This sample code creates a context called /embed.

ServletHttpContext ctx = (ServletHttpContext)
   service.getContext( "/embed" ) ;



if the context does not exist, calling getContext() will create a new context
Next, call addServlet() to map a servlet class to a URI

ctx .addServlet(
   "Simple" , // servlet name
   "/TryThis/*" , // URI mapping pattern
   "sample.SimpleServlet" // class name
) ;



The first parameter is a descriptive name for the servlet. The second parameter is the path to map, equivalent to <url-pattern> in the web.xml servlet mapping. The mapping path is relative to the context path, which is /embed. "/*" means that this servlet receives a URI such as /embed/TryThis, and it also receives all URIs that start with this, such as /embed/TryThis/123. This mapping is very useful when using a single servlet as the entry point to a larger system. Struts and Axis are examples of such mappings used in practical applications.

Sometimes you may want your context to be the root context, or "/", which is more like a normal HTTP service. Jetty supports this through Service.setRootWebapp().
service.setRootWebapp(
   "/path/to/another.war"
) ;



The only parameter is the path to a web application.
The container is still inactive at this point. And it doesn't try to bind the socket to listen on. To start the container, you need to call:

service.start() ;



this method returns immediately because Jetty runs the service in a separate thread. So, while the container is running, main() can do anything else.
The rest of the code uses a set of URLs to call this embedded container. These calls ensure that the container is already running and the servlet is working as expected.
Shutting down a container is as intuitive as starting it

service.stop() ;



Note the catch statement in the outermost try/catch block.

{

   service.start() ;
   // ... URL calls to mapped servlet ...
   service.stop() ;

}catch( Throwable t ){

   System.exit( 1 ) ;

}



The explicit call to System.exit() ensures that The container is closed when an exception occurs. Otherwise, the container keeps running so the entire application doesn't exit.
It must be remembered that Jetty web applications are not limited to being accessed using code. If I take service.stop() out of the code just now, the container will always run and I can call the servlet in the browser, e.g.
http://localhost:7501/embed/TryThis/SomeExtraInfo

you don't have to be completely Do as I say. This sample code can be run as an Eclipse project. And you can also write a shell script to run on the Unix/Linux command line. In both cases above, make sure Jetty is on your classpath.

Separate configuration from code: XML-driven configuration files

Although Jetty's API is very intuitive and concise, calling the Jetty API directly will bury a lot of configuration information - port number, context path, servlet class name - in the code. middle. Jetty provides an XML-based configuration alternative to calling the API directly, so that you can keep your code clean by keeping the configuration information outside the code.

Jetty's XML configuration files are based on Java reflection. Classes in java.lang.reflect represent methods and classes in Java, so that you can instantiate an object and call its methods using the method name and parameter types. In this case, Jetty's XML configuration file parser will translate the XML elements and attributes into reflective method calls.

This code excerpt from the Step2Driver example class is an improved version of Step1Driver. If a configuration file is used, there must be some Jetty code to load it.

URL serviceConfig = /* load XML file */ ;
   // can use an InputStream or URL

XmlConfiguration serverFactory =
   new XmlConfiguration( serviceConfig ) ;

                       
Server service =
   (Server) serverFactory.newInstance() ;



Admittedly, this doesn't save much code over the Step1Driver example , but even if you add a new servlet or web application, the Step2Driver code won't increase because of it. The method of directly calling the Service and context objects will get worse and worse as the configuration increases gradually.
Listing 1 is the XML file loaded by Step2Driver. The attribute of the top-level <Configure> element specifies which class to instantiate. Here is the Jetty Server object.

<!-- 1 -->
<Configure class="org.mortbay.jetty.Server">

  <!-- 2 -->
  <Call name="addListener">
    <Arg>
      <!-- 3 -->
      <New
         class="org.mortbay.http.SocketListener">

        <!-- 4 -->
        <Set name="Host">

          <!-- 5 -->
          <SystemProperty
             name="service.listen.host"
             default="localhost"
          />

        </Set>

        <Set name="Port">
          <SystemProperty
             name="service.listen.port"
             default="7501"
          />
        </Set>

      </New>
    </Arg>
  </Call>


  <Call name="getContext">

    <Arg>/embed</Arg>


    <!--
    call methods on the return value of
    Server.getContext()
    -->

    <!-- 6 -->
    <Call name="addServlet ">

      <!-- servlet name -->
      <Arg>"Simple"</Arg>

      <!-- URL pattern -->
      <Arg>/TryThis/*</Arg>

      <!-- servlet class -->
      <Arg>sample.SimpleServlet</Arg>

    </Call>

  </Call>

</Configure>



The <Call> element represents the method to be called on the Server object. Here to call addListener(), such as mark (2), it has a sub-element called <Arg> , which specifies the parameters of the method. Here I can only pass a string value as the listening address, while addListener() needs to accept a SocketListener object as a parameter. So I'm using <New> to instantiate a new SocketListener object at tag (3). The code at markers 2 and 3 is equivalent to the following code:

server.addListener(
   new SocketListener( ... )
) ;



To configure the SocketListener itself, you must use a <Call> to call its setHost() method. Since this method follows the JavaBean naming rules, the sample code uses <Set > element(4) as a shortcut. In the background, Jetty assigns a value to the property specified by the name property in the set, and decides which method to call. Here is

the parameter of setHost() setHost() is not shown here, but uses <SystemProperty> to get it from the system property Get the value of the parameter, here from the system parameters service.listen.host and service.listen.port. If the system property is not defined, you can use default to specify a default value. Here, 4 and 5 are equivalent to the following call:

   socketListener.setHost(
      System.getProperty(
         "service.listen.host" ,
         "localhost"
      )
  ) ;



finally note that the <Call> element at tag 6 is located in the <Call> that calls the getContext method middle. The inner <Call> acts on the object returned by the outer <Call>. Here, the addServlet() method on the context returned by getServlet() is called:

server.getContext().



The wisdom of the Jetty team lies in the further processing of this XML configuration file: we can notice that all Jetty-specific calls in Listing 1 are element and attribute values, not names, which means that XML configuration files can be used in on any class, not just in Jetty's classes. Depending on how your application is written, you can all configure it using Jetty's XML configuration files.

Executable JARs

If you use Jetty's XML to configure your application, you need to use a lot of repetitive code to load your config file and run your application. But you can use Jetty's executable start.jar to load the files for you, which will save you even more code.

For example, you can use the following command line to load the Jetty service in Step2Driver.

CLASSPATH= ...various Jetty JARs...
java /    -Djetty.class.path
   =${CLASSPATH} /
   -jar <jetty install path>/start.jar/standalone.xml Note that this command only loads xml files to build container and listener, so it doesn't call the code in the sample code to test the URL. Conclusion An embedded Jetty servlet container allows your web to use Java applications without being packaged as a formal web application. This opens up multiple possibilities, making Jetty a versatile addition to your toolbox. Of course, what I've written here doesn't cover everything Jetty has to offer. I suggest you visit Jetty's website for more documentation and sample code.










The above is transferred from http://jiajunde.javaeye.com/blog/373262

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326641993&siteId=291194637