Jetty server knowledge

Source: Internet
Author: User

Jetty server knowledge

Maybe you have never heard of this Jetty server, but it is indeed a lightweight Java Server. Like Tomcat, it specifically explains the JavaWeb program server. Because Tomcat configuration errors and WebRoot directories are always encountered when learning Java Web. The Jetty server can be used directly in the Java project. All we need is to simply import the relevant JAR package, it can also be used as a normal server.

1. Use it directly as a server

Like Tomcat, Jetty can be directly used as a server. I downloaded the latest Jetty9, which can be decompressed directly. To learn about these frameworks, the best resource is the instructions on the official website. Although it is in English, it is not a big problem to use simple sentences. I have learned these basics by referring to the instructions and taking notes to facilitate future use.

At the beginning of the official document, I wrote:

Jetty is an open-source project providing an HTTP server, HTTP client, and javax. servlet container.

This guide is in two parts.

The first part emphasizes beginning to use Jetty. it provides information about downloading Jetty, changing things like the port Jetty runs on, adjusting logging levels, and loading ing history of the most common servlet container features such as JNDI, JMX, and session management.

The second part describes advanced uses of Jetty, providing in depth coverage of specific features like our highly scalable async client, proxy servlet configuration, the Jetty Maven plugin, and using Jetty as an embedded server. the advanced section describes des tutorials, howtos, videos, and reference materials."

It should not be difficult to understand. I mainly talked about Jetty's entry-level usage. Jetty serves as a container feature such as JNDI, JMX, and Session Management. I will continue to explain Jetty's knowledge in depth, for example, Jetty's highly scalable asynchronous client implementation mechanism, proxy server configuration, Maven configuration, and application using Jetty as an Embedded Server.

Start the server first:

Directly decompress the package and run it. However, we need to add the jdk path in the environment variable, and then create JAVA_HOME. Value is the JDK installation PATH, this is because Tomcat cannot be started without adding this variable. If you do not know whether this variable will be used, it is better to add it.

Startup command: java-jar start. jar jetty. port = 8001(You can write a batBatch file or ShellScript)

We will find that the Jetty homepage has nothing, because there is nothing in the root directory, so we need to create an HTML file to see it. Open the browser to view the response results.

Possible problems:

Double-click start. jar, but the server cannot be switched off.

At the beginning, I double-click start. jar can also be run, but the problem arises. I am not sure whether to run it. Then I open the browser and find that the server is running, but how can I terminate it, I did not find it for a long time. In the end, all JAVA services were forcibly destroyed in the process control before the server was terminated. At this time, the ROOT directory of the server is in jetty \ demo-base \ webapps \ ROOT. We recommend that you do not run it like this,

JDK environment configuration problems

The above knowledge is a simple server, but the knowledge is used to run HTML files. Therefore, we should be careful to test the JSP page. Although the server can be started, an error is reported when the code is run:

Http error 500

Problem accessing/. Reason:

Server Error

Caused:

Org. apache. jasper. JasperException: PWC6345: There is an error in invoking javac.A full JDK (not just JRE) is required

At org. apache. jasper. compiler. DefaultErrorHandler. jspError (DefaultErrorHandler. java: 92)

At org. apache. jasper. compiler. ErrorDispatcher. dispatch (ErrorDispatcher. java: 378)

In this way, when the system runs, the system is preferentially used. As A result, the full version of JDK we installed cannot be found, so the system cannot run. A full (not just jre) appears) is required. system error.

In fact, Jetty contains the configuration information about the system before it runs. It is saved in the start. ini file under the same Directory, which contains the knowledge about enabling the JSP service. just delete the previous #.

#

# Initialize module jsp

#

-- Module = jsp

# JSP Configuration

# To use an non-jdk compiler for JSP compilation uncomment next line

#-Dorg. apache. jasper. compiler. disablejsr199 = true

In this way, you can directly run the JSP file. to terminate the program, exit the current window. We can talk about the System log input to the file java-jar start. jar jetty. port = 8001> server. log

2. Some Jetty parameter settings

Jetty. home: The property that defines the location of the jetty distribution, its libs, default modules and default XML files (typically start. jar, lib, etc)

Jetty. base: The property that definesLocation of a specific instance of a jetty server,ItsConfiguration, logs and web applications(TypicallyStart. ini, start. d, logs and webapps)

Jetty. port: jetty start port. This configuration is in the start. d/http. ini file and can be modified.

Java-jar start. jar-add-to-startd = httpd

3. Configure with Maven

<Dependency>

<GroupId> org. eclipse. jetty </groupId>

<ArtifactId> jetty-project </artifactId>

<Version> 9.1.3-SNAPSHOT </version>

</Dependency>

Maybe you still don't know Maven. In fact, I am also a sheet metal engineer. It is generally useful in linux. He will automatically download the response package based on the dependency package, we only need to commission the dependency configuration file.

4. Jetty Embedded Server

Using Jetty as an Embedded Server in Java applications, we can download a full JAR package with the address of http://central.maven.org/maven2/org/eclipse/jetty/aggregate/jetty-all.

Add servlet. jar

Source code:

// TestMain. java

PackageJetty_test;

 

ImportOrg. eclipse. jetty. server. Server;

ImportOrg. eclipse. jetty. server. ServerConnector;

Import;

 

Public ClassTestMain {

 

Public Static VoidMain (String [] args)ThrowsThrowable {

//TODOAuto-generated method stub

Server serverJetty =NewServer ();

ServerConnector connector_one =NewServerConnector (serverJetty );

ServerConnector oror_two =NewServerConnector (serverJetty );

Connector_one.setPort (8000 );

Connector_two.setPort (8001 );

ServerJetty. setConnectors (NewServerConnector [] {connector_one, connector_two });

ServerJetty. setHandler (NewMyHandler ());

ServerJetty. start ();

ServerJetty. join ();

}

}

/*

* Author

* MyHandler. java

*/

PackageJetty_test;

 

ImportJava. io. IOException;

ImportJava. util. Date;

 

ImportJavax. servlet. ServletException;

ImportJavax. servlet. http. HttpServletRequest;

ImportJavax. servlet. http. HttpServletResponse;

 

ImportOrg. eclipse. jetty. server. Handler;

ImportOrg. eclipse. jetty. server. Request;

ImportOrg. eclipse. jetty. server. Server;

 

Public ClassMyHandlerImplementsHandler {

@ Override

Public VoidHandle (String target, Request baseRequest, HttpServletRequest request,

HttpServletResponse response)ThrowsIOException, ServletException {

//TODOAuto-generated method stub

System.Out. Println ("target:" + target );

System.Out. Println (request. getRequestURL (). toString ());

Response. setCharacterEncoding ("UTF-8 ");

Response. setContentType ("text/html; charset = UTF-8 ");

Response. setStatus (HttpServletResponse.SC _ OK);

Response. getWriter (). write ("<B> yangtengfei </B>" + (NewDate ()).);

Response. flushBuffer ();

 

}

/*

The automatically generated code is omitted.

*/

}

The test can be done. This is to embed the WebServer into the application. The most important one is Handle, that is, distributing and processing requests. The input parameter HttpServletRequest & HttpServletResponse, pass the result to response.

For some special cases, in embedded applications, Jetty server parameters may need to be configured. We can use jetty. xml loads the configuration information to XmlConfiguration, and then configures the configuration to the Server. I still haven't configured the configuration successfully. We recommend that you use the Java language for configuration. XML files are not applicable.

5. Theoretical Introduction

Because we have learned how to use the Jetty server, why do we need to understand Jetty's theoretical knowledge. In fact, to learn a part of the knowledge, we should not only learn how to use it, but also know the advantages and disadvantages of this framework knowledge. Under what circumstances should we use this part of knowledge for practical use. What's the good about the Jetty server?

Jetty is a standard-based, cost-effective, Java-based HTTP server and Web Container with rich functions. Jetty's purpose: traditional Web servers, dynamic content servers, and embedded into Java applications.

Features

Ease of use: Use API or XML configuration. The default configuration can meet most of the requirements. Jetty can be embedded into the application, with a very small amount of code.

Scalability: In Ajax Web 2.0 applications, each connection needs to be maintained for a long time, and such thread and memory consumption will increase dramatically, as a result, the overall performance of the program is affected by the bottleneck of a single component in the system. Jetty easily solves this problem:

Even if a large number of service requests exist, the system performance can be maintained in an acceptable state. The Configuration mechanism is used to process a large number of user requests and long connections. At the same time, Jetty has designed a very good interface, so we can modify it based on our own needs.

Easy to embed: Embed Jetty into a Java application, that is, an embedded Web server.

6. Jetty's Configuration Mechanism

In the Ajax technology in the Web 2.0 era, a core object is the XMLHttpRequest object, which supports asynchronous requests (asynchronous requests: when the client sends a request to the server, the client does not have to wait until the server responds. In this way, the real page will not be refreshed to bring a better user experience. When the server returns a response, the client uses a JavaScript function to process the returned value, update the values of some elements on the page.) This kind of request only happens in a small part. What if the client immediately knows the function of implementing this type of server with a response? There are two ways: polling, that is, making the browser request the server at intervals; Comet, maintaining the persistent connection mechanism between the server and the client.

The biggest disadvantage of round-robin is that it produces a large amount of transmission waste. Because many requests are invalid and occupy a large amount of bandwidth resources, the load on the server is aggravated. Especially for the mail system, it takes a long time to update. If the set interval is long, the client cannot get a timely response.

With Comet technology, the client must ensure a persistent connection. In general, each Servlet on the server occupies a single thread, which causes a large number of threads on the server to exist at the same time. When there are many clients, this poses a huge challenge to the server's processing capabilities.

In Java, the non-blocking I/O technology of Java is used to process a large number of concurrent connections. Jetty processes persistent connections: A feature called Configuration, Jetty can use a thread to simultaneously process asynchronous requests sent by multiple clients:

Public class ChatContinuation extends HttpServlet {

Public void doPost (HttpServletRequest request, HttpServletResponse response ){

PostMessage (request, response );

}

Private void postMessage (HttpServletRequest, HttpServletResponse response ){

HttpSession session = request. getSession (true );

People people = (People) session. getConfiguration (request, this );

If (! People. hasEvent ()){

Continuation continuation = Continuation. getContinuation (request, this );

People. setContinuation (continuation );

Continuation. suspend (1000 );//At this time, the thread is suspended and can process other requests. This greatly improves the concurrent performance of the program and improves the scalability of persistent connections.

}

People. setContinuation (null );

People. sendEvent (response );

}

}

If you do not use the Continuation mechanism, you can only use the thread to suspend and wait. See the following code:

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 = (People) session. getAttribute (session. getId ());

While (! People. hasEvent ()){

Try {

Thread. sleep (1000 );

} Catch (InterruptException e ){

E. printStack ();

}

}

}

}

Jetty's Continuation mechanism:

With the Continuations mechanism, Jetty must be configured to use its selectchannelctor ctor to process requests. This jetctor is built on java. nio. API, allowing it to maintain each connection without having to make a small county seat. When SelectChannelConnector is used, ContinuationSupport. getContinuation () provides a SelectChannelConnector. RetryContinuation instance. When the suspend function is called on RetryContinuation, a running exception is thrown. This exception is passed to the filter chain and finally captured by SelectChannelConnector. However, requests are not sent to the client, but are kept in the pending Continuation 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 Continuation queue until the specified expiration time, or calls resume () on its Continuation (). When any of the conditions is triggered, the request will be resubmitted to the Servlet (through the Filter chain), and the entire request process will be replayed, knowing that the RetryRequest exception is not thrown, then run the command as normal.

 

In Guangzhou

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.