Ninja Web Framework Documentation

repository·develop·Indexed 23 days ago

https://github.com/ninjaframework/ninja

A full-stack web framework for Java focusing on speed, reliability, and developer productivity. Supports Java 8, 11, 17, and 19/21. Documentation covers core concepts like the @Start annotation for startup logic, argument extractors for controller parameter injection, servlet integration testing with Docker, and developer guidelines for contributions and releases.

Tokens
50.4K
Snippets
136
Records
253
Agent score
83%

What's inside Ninja

  1. Available testing tools in Ninja

    develop

    Ninja provides several specialized testing approaches depending on your needs:

    • Mocked Tests: For testing parts of your application in isolation.
    • NinjaTest: For testing a running server at the HTTP level.
    • NinjaDocTester: Ideal for documenting and testing JSON APIs.
    • NinjaFluentLeniumTest: The recommended way to test HTML elements via Selenium on your Ninja application.
  2. Ninja technology stack overview

    develop

    Ninja is an integrated software stack that provides the following capabilities out of the box:

    Frontend

    • HTML rendering: Freemarker
    • JSON/XML rendering & parsing: Jackson

    Stateful RESTful features

    • Session & Authentication: ninja-session
    • Flash scope: ninja-flash

    Core Libraries

    • Dependency Injection: Guice
    • Configuration: Multiple environment configuration (Ninja)
    • Internationalization (i18n): Support for templates and controllers (Ninja)
    • Lifecycle Management: Ninja lifecycle
    • Mail: Mail sending support
    • Scheduling: Scheduler support
    • Validation: JSR 303 object validation (Hibernate-validation)
    • Utilities: Google Guava
    • Logging: slf4j and logback

    Data Persistence & Caching

    • Relational Data: JPA (Hibernate) and Database migrations (Flyway)
    • Cache Layer: Memcached and EhCache

    Testing Support

    • Mocking: Mockito
    • Framework Testing: NinjaTest
    • Documentation Testing: NinjaDocTester
    • Browser/UI Testing: NinjaFluentLeniumTest
  3. Available Ninja modules by category

    develop

    Ninja is an extensible framework. You can add functionality by integrating various modules for runtime platforms, server engines, template engines, databases, authentication, and more.

    Runtime Platforms

    • Google AppEngine Support: https://github.com/ninjaframework/ninja-appengine

    Server Engines

    • Undertow standalone: An alternative to Jetty via https://github.com/fizzed/ninja-undertow

    Template Engines

    • Rythm templates: https://github.com/ninjaframework/ninja-rythm
    • Mustache templates: https://github.com/kpacha/ninja-mustache
    • Jade4Ninja (Jade) templates: https://github.com/mysu/jade4ninja
    • Rocker templates: https://github.com/fizzed/ninja-rocker
    • Pebble templates: https://github.com/jjfidalgo/ninja-pebble or https://github.com/bordereast/ninja-pebble-module

    Databases and ORM

    • EBean RDBMS ORM (for EBean <= 7.2.3): https://github.com/ninjaframework/ninja-ebean
    • EBean RDBMS ORM (for EBean > 7.2.3): https://github.com/jfendler/ninja-ebean-ng
    • MongoDB/Morphia Integration: https://github.com/bihe/ninja-mongodb
    • Cassandra: https://github.com/fizzed/cassandra-plus

    Authentication

    • Auth0 (SaaS): https://github.com/zileo-net/ninja-auth0

    Process Engines

    • Activity (Workflow/BPM): http://mortezaadi.github.io/ninja-activiti-module/
    • Camunda BPMN Integration: http://github.com/FendlerConsulting/ninja-camunda
    • Executors (Long lived tasks): https://github.com/fizzed/executors

    Miscellaneous

    • Prometheus (Metrics): https://github.com/fizzed/prometheus-plus
    • Redis (Cache/Pooling): https://github.com/fizzed/redis-plus
    • RabbitMQ (Pooling/Sessions): https://github.com/fizzed/rabbitmq-plus
    • Hazelcast Cache: https://github.com/raptaml/ninja-hazelcast-embedded
    • Quartz Scheduler: https://github.com/FendlerConsulting/ninja-quartz
    • Sitemap Generator: https://github.com/FendlerConsulting/ninja-sitemap
  4. Compare Ninja support plans

    develop

    Ninja offers three yearly support plans to assist with development best practices, deployment options, and bug reporting. Plans differ by maximum monthly support hours, response times for regular and critical incidents, and eligibility for priority bugfixes.

    FeatureStandardPremierMission critical
    Email supportYesYesYes
    Phone supportYesYesYes
    Max support time/month3h10h20h
    Response (Regular)24h18h12h
    Response (Critical)24h12h1h
    Priority bugfixesNoYesYes

    If your plan includes priority bugfixes, reported bugs are guaranteed to be fixed in the next release.

  5. What is Flash scope?

    develop

    The Flash scope is a mechanism for transporting success and error messages between stateless web applications. It is implemented as a client-side cookie, similar to a Session, but it is not signed.

    Flash messages have two primary lifecycles:

    1. Current request only: The message is available only for the immediate request.
    2. Current and next request: The message is available for the current request and the subsequent request, after which it is automatically deleted.
  6. Understand JSON and XML error representations

    develop

    Ninja uses content negotiation to return errors in JSON or XML formats if the client sends the appropriate Accept header (application/json or application/xml).

    Errors are rendered as a ninja.util.Message object containing a text field and an error field.

    JSON Format Example:

    {
        "text": "Oops. The requested route cannot be found.",
        "error": "My exception localized message."
    }

    XML Format Example:

    <Message>
        <text>Oops. The requested route cannot be found.</text>
        <error>My exception localized message.</error>
    </Message>
  7. Important considerations when using the Servlet bridge

    develop

    When combining Ninja with Servlet-based components, keep the following architectural constraints in mind:

    1. Scalability and Sessions: Ninja is a stateless framework and does not use Servlet sessions. If you introduce Servlets or Filters that rely on HttpSession, you lose the ability to scale your Ninja application easily. For session management, it is recommended to use Ninja's native session mechanism instead of Servlet sessions.
    2. Runtime Compatibility: The ServletModule approach only works when Ninja is running inside a Servlet container (e.g., Tomcat, Jetty). It will not work if you are running Ninja inside a Netty application, as Netty does not implement the Servlet specification.
  8. Automatic object parsing and Context injection

    develop

    Ninja can automatically inject the Context object, which holds all information about the current request (parameters, headers, etc.).

    Additionally, Ninja can automatically parse arbitrary objects passed as method arguments. The parsing format (JSON, XML, or POST form) is determined by the Content-Type request header.

    For POST forms, Ninja supports nested objects using dot notation. For example, if a User object contains an Address object with a street field, a form field with the key address.street will be correctly mapped.

    package controllers;
    
    @Singleton
    public class ApplicationController {
    
        public Result index(
                @PathParam("id") String id, 
                @PathParam("email") String email, 
                @Param("debug") Optional<String> debug,
                @Param("isAdmin") Boolean isAdmin,
                Context context,
                MyObject myObject) {
    
            // do something with the parameters...
        }
    }
  9. Switch between RecycledNinjaServerTester and FreshNinjaServerTester

    develop

    Ninja provides two primary testing base classes depending on your isolation needs:

    1. RecycledNinjaServerTester: Starts a single Ninja test server for all tests in a JUnit test class. Use this for high-performance testing when tests do not rely on a fresh server state.
    2. FreshNinjaServerTester: Starts a new Ninja test server for every individual test method. Use this if your tests require complete isolation or a clean server state for every execution.
  10. Define application messages with .properties files

    develop

    Messages are stored in files following the naming convention messages_LANGUAGE.properties or messages_LANGUAGE-COUNTRY.properties.

    Ninja uses a hierarchical lookup for messages (from most specific to least specific):

    1. messages_en-US.properties (if requested)
    2. messages_en.properties (fallback)
    3. messages.properties (global fallback)

    Formatting: Ninja uses java.text.MessageFormat. To use a literal apostrophe ' in your message, you must escape it by using two apostrophes ('').

    Example conf/messages_en.properties:

    # registration.ftl.html
    casinoRegistrationTitle=Register
    casinoYourUsername=Your username is: {0}