In this example we will create an async servlet that adds contacts to a list, parses requests and processes form
validation with the help of
Decoder. Consider this example as a concise representation of the MVC pattern:
- To model a
Contactrepresentation, we will create a plain Java class with fields (name, age, address), constructor, and accessors to the fields.
- To simplify the example, we will use an
ArrayListto store the
ContactDAOinterface and its implementation are used for this purpose.
- To build a view we will use a single HTML file, compiled with the help of the Mustache template engine.
AsyncServletwill be used as a controller. We will also add
RoutingServletfor routing a concrete request to a particular endpoint.
- Decoder provides you with tools for parsing requests.
Here we will consider only
HttpDecoderExample class with
AsyncServlet as it contains ActiveJ-specific features.
HttpDecoderExample class which extends
HttpServerLauncher. By extending
HttpServerLauncher we will take care
of the server's lifecycle and service management. Next, we provide two custom parsers based on HTTP
CONTACT_DECODER - which will be used for validation.
If you want to learn more about template engines integration, check out this example
Also, we need to create applyTemplate(Mustache mustache, Map<String, Object> scopes) method to fill the provided Mustache template with the given data:
Next, let's provide a ContactDAOImpl factory method:
Now we have everything needed to create
AsyncServlet to handle requests:
- Here we provide an
AsyncServlet, which receives
HttpRequestsfrom clients, creates
HttpResponsesdepending on route path and sends it.
- Inside the
RoutingServlettwo route paths are defined. The first one matches requests to the root route
"/"- it simply displays a contact list. The second one,
"/add"- is an HTTP
POSTmethod that adds or declines adding new users. We will process this request parsing with the help of the aforementioned HTTP
- Either represents a value of two possible data types (
DecodeErrors). Either is either Left(
Contact) or Right(DecodeErrors). In order to determine whether a parse was successful or not, we check it's value by using the
Finally, write down the
main() method which will launch our application:
If you want to run the example, you need to clone ActiveJ from GitHub and import it as a Maven project. Check out branch v4.3. Before running the example, build the project (Ctrl + F9 for IntelliJ IDEA).
HttpDecoderExample class, which is located at
activej/examples/tutorials/decoder and run its
main() method. Open your favourite browser and go to localhost:8080