Skip to content

Latest commit

 

History

History
313 lines (177 loc) · 15.9 KB

README.adoc

File metadata and controls

313 lines (177 loc) · 15.9 KB

Vert.x-Web examples

Here you will find examples demonstrating Vert.x-Web in action.

Vert.x-Web is a tool-kit for writing web applications with Vert.x. Please consult the Vert.x-Web manual for detailed documentation on Vert.x-Web.

Logging

When running in an IDE you can edit src/main/resources/vertx-default-jul-logging.properties to configure logging. Trace logging is enabled for Vert.x-Web classes, so you can easily trace requests as they are routed through different handlers.

Dependencies required

To use Vert.x-Web in your own Maven or Gradle project you will need following dependencies

Group ID: io.vertx
Artifact ID: vertx-core

and

Group ID: io.vertx
Artifact ID: vertx-web

If you’re using a template engine you will also need to add the engine dependency explicitly, depending on the engine you are using.

Hello World

The traditional hello world example.This one creates a server which just responds with "Hello World! to each request.

Simple REST Microservice

Vert.x-Web is a great fit for HTTP/REST microservices.

Here’s a simple microservice example which implements an API for a product catalogue.

The API allows you to list all products, retrieve details for a particular product and to add a new product.

Product information is provided in JSON.

List all products

GET /products

Get a product

GET /products/<product_id>

Add a product

PUT /products/<product_id>

Run the server in your IDE, then open your browser and hit list products to start playing with the API.

Site with templating

This example shows a simple web-site containing some static pages and also a page dynamically generated using templates.

Multiple examples with different templating engines, including FreeMarker, Handlebars, MVEL, Pebble, Rocker, and Thymeleaf are available.

Run the server in your IDE, then open your browser and hit localhost:8080 and click on the links

Sessions example

This example shows how to use sessions with Vert.x-Web. Sessions are available between requests and last the length of the browser session.

The example increments a counter in the session every time a request hits the server.

Run the server in your IDE, then open your browser and hit localhost:8080 then refresh the page a few times - you should see the hit count increase.

Note
Depending on your browser you may see it increase by two each time you refresh!Why is that?Some browsers will actually send two HTTP requests every time you refresh - one to request the favicon for the site and one to request the actual page.

Real-time - client side event bus

This example demonstrates a full duplex connection between the browser and the server side.

The connection remains open, so you can communicate easily between server and browser or server and browser by just sending messages over the event bus, like you would on the server side.

It uses the SockJS event bus bridge to effectively extend the Vert.x event bus to the client side, so you can interact with server side event bus services from client side JavaScript. SocksJS gives a WebSocket-like API in client side JavaScript even if the browser or network doesn’t support WebSockets.

This is ideal for so-called real-time web applications where you want quick, responsive communication between server and client, and you’re probably rendering the user interface on the client side.

Run the server in your IDE, then open your browser and hit link:http://localhost:8080

This serves the index page which contains some JavaScript which opens an event bus connection to the server.

When the connection is open, a handler is registered on the event bus against the address news-feed.When data arrives in the handler the script just uses some simple JQuery to write the message to the page.

On the server side, in the server we set a periodic timer that fires every second and sends a message to the news-feed address.

When you get the index page in your browser you should see it update every second as it receives a message.

Real-time - chat service

This example demonstrates 2-way communication between the client and the server using the event bus bridge and web sockets.

The index.html file bootstraps the vertxbus.js bridge from the client and uses jQuery to handle manipulating the DOM and registering event handlers.

When you load the index page in a browser, you should see a div for chat messages and an input field where you can enter your own messages. Typing in the input field and pressing ENTER will cause the input to be sent via the event bus to the server. The server will accept the message, prepend it with a timestamp and publish back to all registered listeners (e.g. All connected clients). Take note of the addInboundPermitted and addOutboundPermitted settings on the BridgeOptions object to be sure that you authorize the correct messages to traverse the event bus bridge in the appropriate direction.

To run the example, run Server.java in your IDE by right-clicking, or at the command line, and point your browser at link:http://localhost:8080

Auth example

This example shows a basic static web-site that contains both public pages and pages that are only accessible to a logged-in user.

Requests to paths starting with /private/ will require login.

The example uses a simple auth service which gets user/password/role information from a properties file src/main/resources/vertx-users.properties.

The type of login used here is redirect login.If a request is made to a private resource and the session isn’t already logged in a redirect will be sent to the browser causing it to load the login page.When the login form is submitted it is handled by the form login handler which then redirects the browser back to the originally requested resource if login was successful.

Run the server in your IDE, then open your browser and hit link:http://localhost:8080 and click around the links

This example shows a basic user Tracking system based on Cookies.On each page refresh a cookie is incremented with the number of visits.

CORS example

This example shows how to set up the CORS Handler. Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts, JavaScript, etc.) on a web page to be requested from another domain outside the domain from which the resource originated.

CORS requests fall in two types, request that require a pre-flight check and requests that do not require it.HTTP GET does not require such a check while other HTTP verbs do.When the CORS handler is active the Origin header is checked to allow, disallow the request.

In order to run the example, you need to download the 2 example HTML pages and run them from your hard disk.If you are using a modern browser when clicking on the links they will pop up the download pop-up, however this might not work for older browsers.

If the CORS Handler is not present, then only the no preflight check call will work, since the browser will disallow the POST.

Run the server in your IDE, then open your browser and hit link:http://localhost:8080 and click around the links

Upload example

This example shows a basic HTML form file upload and returns the upload metadata.

The home request will return an HTML form with a simple input type file and will upload the file in multipart encoding. On submit the file will be handled by the BodyHandler and be available in the RoutingContext using the getter fileUploads.

HTML Form example

This example shows a basic HTML form web-site and a backend end point that just returns a customizable hello world message.

Run the server in your IDE, then open your browser and hit link:http://localhost:8080 and click around the links

JWT example

This example shows a basic single page application that contains an API that is protected by a JWT.

Requests to paths starting with /api/ will require a JWT token, except the excluded /api/newToken. This exclusion is normally used as the login end point, however in this example we are not focusing on secure login end points, and we just return a new token for any request.

The application contains a simple form where you can request some data from the API if there is no token loaded then the response is an HTTP error 401. When a token is loaded, then a successful response if received from the API.

Run the server in your IDE, then open your browser and hit link:http://localhost:8080 and click around the links

Blocking handler example

This example shows a blocking handler which blocks the calling thread for 5 seconds before calling the next handler to serve the page.

Blocking handlers are run on a worker thread and don’t block an event loop.

Run the server in your IDE, then open your browser and hit link:http://localhost:8080 - after 5 seconds the response should arrive.

Static web server example

This example shows a very simple web server which serves static files from disk.

The server can be run either in your IDE with the main class or at the command line.

SQL Client example

This example shows a basic REST server backed by a SQL client. It is exactly the same as the REST client however its data is persisted in a relational database using the asynchronous SQL client.

Run the server in your IDE, then open your browser and hit link:http://localhost:8080/products to get the list of products, or link:http://localhost:8080/products/0 for accessing a product with id 0. In order to create new products use the POST method to link:http://localhost:8080/products

Auth SQL example

This example shows a basic static web-site that contains both public pages and pages that are only accessible to a logged-in user. This is a remake of the auth example, however using a different auth provider. In this case it uses the SQL Client Auth Provider.

Requests to paths starting with /private/ will require login.

The username/password are loaded from the set upInitialData method.

Run the server in your IDE, then open your browser and hit link:http://localhost:8080 and click around the links

Angular realtime example

This example shows a music store implemented with angular js, where all album data and orders are taken in realtime.The example expects that there is a local instance of mongo db running.

It also demonstrates how to protect the even bus when used with a bridge using one Auth Provider.

The example uses a simple auth service which gets user/password/role information from a properties file src/main/resources/vertx-users.properties.

Run the server in your IDE, then open your browser and hit link:http://localhost:8080 and click around the links

Programmatic Authentication examples

This examples shows how to use the Auth Handlers to protect resources by asserting if the user has the right authorities to access the resource.

There are 2 implementations, one using the API to verify assertions, and a second where assertions are implemented in code:

The example shows 4 resource that require different authorities:

  • (none) link:http://localhost:8080/api/protected

  • defcon1 link:http://localhost:8080/api/protected/defcon1

  • defcon2 link:http://localhost:8080/api/protected/defcon2

  • defcon3 link:http://localhost:8080/api/protected/defcon3

You can generate different tokens with different authorities and test it. The example html does not generate defcon3 tokens, in order to show that you cannot access the last resource.

Run the server in your IDE, then open your browser and hit link:http://localhost:8080 and click around the links

HTTP2

The HTTP2 example is a simplified Chuck Norris test.The important thing to note is that there is no API differences between HTTP1.1 and HTTP2 regarding web.The only change is the bootstrap of the server.

React.js Realtime chat

This example shows how you can integrate Vert.x EventBus SockJS bridge in a simple React.JS application. Since React is written in ES6 + JSX you will need to use webpack to bundle you client application, for this run npm install to install all the dependencies locally, and later you can compile your client application with: ./node_modules/.bin/webpack -p

Important files to note:

Run the server in your IDE, then open your browser and hit link:http://localhost:8080 and chat with a couple of browser windows!

OAuth2

The OAuth2 example is a simplified interaction with GitHub OAuth2 server.It will show how to secure and authenticate users, plus requesting specific authorities:

  • user:email

Plus how to interact with secured resources using the user object directly.

HTTP Request Validation and OpenAPI 3 Router Factory

The ValidationExampleServer is an example of various usages of validation capabilities included in Vert.x Web API Contract package

The OpenAPI3Server is an example of OpenAPI3RouterFactory, the interface to build your design driven router based on your OpenAPI specification.

Web Proxy example

This example shows how to proxy requests to an external backend with Vert.x-Web. The backend is just an external server that is not required to be hosted on the same computer. .

The example redirects all plain requests to /foo on local port 8080 to port 7070.

A second example redirects after HTTP Basic Authentication all requests to /private on local port 8080 to port 7070.

Note
The backend for the second example is totally unprotected. The example is showing that you can mix other handlers with the ProxyHandler like you would on a typical vertx-web application.

gRPC example

The Server is an example of integrating a routing gRPC traffic to a gRPC server.