Jetty you don't know.

Source: Internet
Author: User
Embedded jetty this article describes how to use embedded jetty to create an http/https server. i. related jar package Jetty-serverJetty-servlet 2. creation Method 2.1) simplest ServerservernewServer (8080); server. start (); server. join (); create...

Embedded jetty

This article describes how to use the embedded jetty to create an http/https server.

1. Related jar packages
Jetty-server
Jetty-servlet

Ii. Creation Method
2.1) the simplest
 
Server server = new Server (8080 );
Server. start ();
Server. join ();
Create a jetty server and start it. In this way, we create a simple http server and check that port 8080 is in the listening status, but obviously, the server does not respond to client requests.

2.2) Handler

1) Implementation
In terms of implementation, jetty server itself is a HandlerWrapper. You can set handler for the server to process client requests.

 
Server server = new Server (8080 );
Server. setHandler (newHelloHandler ());
Server. start ();
Server. join ();
Implement the handle method by extending the javasacthandler class and define your own handler, for example:

 
Public class HelloHandler extends+acthandler {
Public void handle (String target, Request baseRequest,
HttpServletRequest request, HttpServletResponse response)
Throws IOException, ServletException {
Response. setContentType ("text/html; charset = UTF-8 ");
Response. setStatus (HttpServletResponse. SC _ OK );
BaseRequest. setHandled (true );
Response. getWriter (). println ("
Hello World


");
}
}
2) test
Enter:

Http: // localhost: 8080
Output:

Hello World
2.3) Servlet
Directly set Handler for the Server. We cannot implement different processing logic for different URL paths. For example,
When the browser inputs the following URL, the server will handle the difference:

Http: // localhost: 8080 /*

Http: // localhost: 8080/TYPE1 /*

Http: // localhost: 8080/TYPE2 /*
1) Implementation
Add ServletContextHandler to the Server, and then set the Servlet for processing based on different paths.

 
Server server = new Server (8080 );
ServletContextHandler context = new ServletContextHandler (
ServletContextHandler. SESSIONS );
Context. setContextPath ("/");
Server. setHandler (context );
Context. addServlet (newServletHolder (newHelloServlet ()),"/*");
Context. addServlet (newServletHolder (newHelloServlet (
"TYPE1 Request"), "/TYPE1 /*");
Context. addServlet (newServletHolder (newHelloServlet (
"TYPE2 Request"), "/TYPE2 /*");
Server. start ();
Server. join ();
Define your own Servlet by extending HttpServlet to overwrite the doPost or doGet methods, for example:

 
Public class HelloServlet extendsHttpServlet {
String greeting = "Hello ";
Public HelloServlet (){
}
 
Public HelloServlet (String hi ){
Greeting = hi;
}
 
@ Override
Protectedvoid doGet (HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Response. setContentType ("text/html ");
Response. setStatus (HttpServletResponse. SC _ OK );
Response. getWriter (). println ("


"+ Greeting +"

");
}
 
@ Override
Protectedvoid doPost (HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
DoGet (request, response );
}
}
2) test
Enter:

Http: // localhost: 8080 /*

Http: // localhost: 8080/TYPE1 /*

Http: // localhost: 8080/TYPE2 /*
Output:

Hello
TYPE1 Request
TYPE2 Request
2.3) Connector

The http/https server can also provide services on multiple ports at the same time, which requires the introduction of Connector

1) Implementation
The following code sets two ctor s, one using port 8080 and the other using port 8888:

 
Server server = new Server ();
Selectchannelconneconnectconnector0 = new SelectChannelConnector ();
Connector0.setPort (8080 );
Connector0.setMaxIdleTime (30000 );
Connector0.setRequestHeaderSize (8192 );
 
Selectchannelconneconnectconnector1 = new SelectChannelConnector ();
Connector1.setPort (8888 );
Connector1.setMaxIdleTime (30000 );
Connector1.setRequestHeaderSize (8192 );
 
Server. setConnectors (newConnector [] {connector0,
Connector1 });
Server. setHandler (newHelloHandler ());
Server. start ();
Server. join ();
2) test
Enter:

Http: // localhost: 8080 /*
Or

Http: // localhost: 8888 /*
Iii. https Server
This section describes how to create an https server.

3.1) keystore
Use the keytool command to create a keystore. For example:

Keytool-keystore zenithKS-alias zenith-genkey-keyalg RSA
Enter keystore password:
Re-enter new password:
What is your first and last name?
[Unknown]: zenith

What is the name of your organizational unit?
[Unknown]: zenith

What is the name of your organization?
[Unknown]: zenith

What is the name of your City or Locality?
[Unknown]: bj

What is the name of your State or Province?
[Unknown]: bj

What is the two-letter country code for this unit?
[Unknown]: cn

Is CN = zenith, OU = zenith, O = zenith, L = bj, ST = bj, C = cn correct? (Type "yes" or "no ")
[No]: yes

Enter key password :
(RETURN if same as keystore password ):
You need to enter the keystore password and key password. At last, a zenithKS file is generated in the current directory. This is the keystore file.

3.2) ssl ctor
To set ssl ctor for jetty Server, you must specify the keystore path, keystore password, and key password.

 
Server server = new Server ();
Sslselectchannelconnessl_connector = new SslSelectChannelConnector ();
Ssl_connector.setPort (8443 );
SslContextFactory cf = ssl_connector.getSslContextFactory ();
Cf. setKeyStore ("D: \ keystores \ zenithKS ");
Cf. setKeyStorePassword ("password ");
Cf. setKeyManagerPassword ("password ");
Server. addConnector (ssl_connector );
Server. start ();
Server. join ();
Enter:

Https: // localhost: 8443 /*
3.3) https client
HttpClient provides SSL support. The following describes how to automatically accept certificates by extending the HttpClient class.

Because this method automatically receives all certificates, there are certain security issues, so please carefully consider your system security requirements before using this method. The procedure is as follows:

1) provide a custom socket factory (test. MySecureProtocolSocketFactory ). This custom class must implement the interface

Org. apache. commons. httpclient. protocol. SecureProtocolSocketFactory
Call the custom

X509TrustManager (test. MyX509TrustManager)
The two classes can be obtained in the attachment with this document.

2) create an org. apache. commons. httpclient. protocol. Protocol instance and specify the protocol name and default port number.

Protocol myhttps = new Protocol ("https", new MySecureProtocolSocketFactory (), 443 );
3) register the created https protocol object

Protocol. registerProtocol ("https", myhttps );
4) Open the https target address in normal programming mode.

Related Article

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.