Version 8

    TODO: Update links to new as-quickstart repository when completed


    This article details the sigificant files, libraies, and source code for the AeroGear archetype and quickstart that is part of the JBoss-AS quickstart suite called "jboss-as-html5-mobile".


    The quickstart example is the direct product of the archetype, and for that reason this article will use the quickstart of reference, but same files will exist if you create your own application using the archetype.  For instructions on getting started with the archetype and quickstart see: Getting Started With HTML5 Mobile Web Development with JBoss

    Client Side

    The client side of this quickstart consists of single page application (index.html), its dependent libraries, and other standard resources (JavaScript, CSS, images). 


    Github Source: index.html


    For this application we chose to follow the single page application approach where your entire client application can be encapsulated into a single html file.  While this may sound crazy at first there are actually some very good reasons to do this, especially if it fits your use-case.  For more complex use-case other approaches may be appropriate.


    From the header of the document you can see that this is a HTML5 file because of the <!DOCTYPE html> tag.  We then set the <meta> tags to define the scaling and viewport properties for our application.  In our case we don't want to allow zooming, and we're setting the initial width of the page to the width of the device.


    After this comes out 3rd party libraries that we are using and described more in their own section below.  We also pull our own app.js file which contains the majority of our JavaScript logic.


    <!DOCTYPE html>
        <title>JBoss HTML5/Mobile Application</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <!-- Set viewport scaling and zoom features -->
        <meta name="viewport" content="width=device-width, initial-scale=1;"/>
        <!-- Include the full development version of Modernizr. In production, you should use a -->
        <!-- minimized custom build to reduce file size -->
        <script type="text/javascript" src="resources/js/modernizr-2.0.6.js"></script>
        <script type="text/javascript" src="resources/js/yepnope.1.0.2-min.js"></script>
        <script type="text/javascript" src="resources/js/underscore-min.js"></script>
        <script type="text/javascript" src="resources/js/app.js"></script>


    Directly after this part of the header comes our initialization logic for our application.  In this section we do a couple of different things:


    1. Demonstrate how to use the yepnope library to conditionally load the jquery-min.js file from a CDN, or fallback to our own local non-minified version for development.
    2. Use Modernizr and new media queries to determine if this is a mobile device
      1. Using this information we toggle jQuery mobile support, and which CSS files to include in our app
    3. When that is completed we setup our initial event listeners, and populate the member table from the server.
    HTML5 Semantic Tags & Structure

    One of the new features of HTML5 is a whole suite of new semantic based tags.  By which I mean <section>, <footer>, <aside>, etc....  These make it possible to easily break up your structure without ending up with a forest of  <div id=""> tags all over your document.


    In the quickstart application we use them to break up the different sections of the page, define the footer, and various articles in the application. By having the desktop version of the application broken up in this way, it makes moving to a mobile browser using jQuery Mobile much easier.  Each article is a different page, the aside is the "info" link, etc...




    We also use CSS rules to "hide" various parts of the page based on the client type, and format.  This is helped by the media queries described above, and also by how jQuery Mobile defines its page sections.

    HTML5 Form API

    Another new feature of HTML5 and its related specifications are the HTML form elements and API.  In the quickstart we use several of the new features in the member form.


                                <legend>Register a user:</legend>
                                    <label for="name">Name:</label>
                                    <input type="text" name="name" id="name" placeholder="Your Name" required autofocus/>
                                    <label for="email">Email:</label>
                                    <input type="email" name="email" id="email" placeholder="Your Email" required/>
                                    <label for="phoneNumber">Phone #:</label>
                                    <input type="tel" name="phoneNumber" id="phoneNumber" pattern="[0-9]{10,12}" placeholder="Your Phone #" required/>
                                <div id="formMsgs"></div>
                                <div data-role="controlgroup" data-type="horizontal">
                                    <input type="submit" name="register" id="register" value="Register"/>
                                    <input type="button" name="cancel" id="cancel" value="Cancel"/>


    Input type attribute

    By setting input type attribute based on the type of field it represents browsers can make various optimizations.  Mobile browsers that support this attribute (iOS) will display special optimized keyboards - as shown below.  Some desktop browsers (webkit) will automatically validate the field as well.  For example checking that the field is a valid email. 



    Placeholder and Autofocus

    You can also see the use of the "placeholder" and "autofocus" attributes.  The placeholder attribute allow you to set a default text string that will display in your field when there is no value.  This is great, especially for mobile devices where you can shrink or eliminate other labels for fields.  The autofocus attribute is exactly as you would expect, for browsers that support this tag the keyboard/input focus will automatically be on the specified fields.


    Input Validation

    One of the more critical updates to the form fields is around built in, client validation.  You'll notice attributes like "required" and "pattern".  These along with input type discussed above allow browsers that support it to validate fields on the client side.  For now this is limited to desktop Chrome, Safari, and Firefox, and their support is slightly different, but improvements are made all the time in this area. 


    Note: it is important that any validation you enter here should match the Bean Validation from class above.  We'll be looking to make this process easier and/or automated for you in the future!


    Github Source: app.js

    CSS Files

    Github Source: CSS directory


    3rd Party Libraries

    Github Source: JavaScript directory

    Server Side

    The server side of this application consists of a basic domain model using Bean Validation, and JAX-RS service endpoints using RESTEasy to provide access.

    Github Source:


    @Table(name = "MemberHTML5", uniqueConstraints = @UniqueConstraint(columnNames = "email"))
    public class Member implements Serializable {
       /** Default value included to remove warning. Remove or modify at will. **/
       private static final long serialVersionUID = 1L;
       private Long id;
       @Size(min = 1, max = 25, message = "1-25 letters and spaces")
       @Pattern(regexp = "[A-Za-z ]*", message = "Only letters and spaces")
       private String name;
       @Email(message = "Invalid format")
       private String email;
       @Size(min = 10, max = 12, message = "10-12 Numbers")
       @Digits(fraction = 0, integer = 12, message = "Not valid")
       @Column(name = "phone_number")
       private String phoneNumber;


    Here you can see the domain object that is the base of our quickstart.  This class has three fields (Name, Email, and PhoneNumber).  It uses Bean Validation annotations to define constraints for each of these fields so that only valid values will be accepted.


    Also note that at the top we are defining a table name for this object, and specifying that the Email field must be unique in the data table.  This will come into play later when need to validate this in the JAX-RS services, and process the response codes effectively.

    Github Source:


    This class contains the actual RESTful endpoint definitions and processing code.  It uses RESTEasy which is JBoss's implementation of the JAX-RS specification to make this easy to do, and configure using annotations.  A general discussion of JAX-RS is beyond the scope of this document but checkout the RESTEasy site for more!


    public class MemberService {


    Any requests to /members will be routered to this class and be processed by its methods that are defined below.


       public List<Member> listAllMembers() {
       public List<Member> listAllMembersJSON() {
       public Member lookupMemberById(@PathParam("id") long id) {
       public Member lookupMemberByIdJSON(@PathParam("id") long id) {


    The methods above define the different ways of "getting" data from the service.  No only can you get a full list of members, and individual members, you can get them in either XML, or JSON format.  The power of JAX-RS is that these are automatically marshaled from one form to another - we are just dealing with POJOs!


    Adding members is where it gets more interesting.  Following RESTful conventions we use POST requests to create new objects in the data base.  We define that using the @POST annotation.


       public Response createMember(@FormParam("name") String name, @FormParam("email") String email, @FormParam("phoneNumber") String phone) {
          Response.ResponseBuilder builder = null;


    JAX-RS allows our method to accept standard URL encoding form variables, and make it easy to map these to method parameters using the @FormParam annotation. 


          //Create a new member class from fields
          Member member = new Member();


    Using those values it then constructs a new member object.  We don't want to just commit this to the database though.  We want to make sure it is valid first!


          try {
             //Validates member using bean validation


    The validateMember method validates the given Member variable and throws validation exceptions based on the type of error.  If the error is a standard bean validation violation then it will throw a ConstraintValidationException containing a set of the constraints violated.  If the error is caused because an existing member with the same email is registered it throws a regular validation exception so that it can be interpreted separately by the catch block.


          } catch (ConstraintViolationException ce) {
             //Handle bean validation issues
             builder = createViolationResponse(ce.getConstraintViolations());
          } catch (ValidationException e) {
             //Handle the unique constrain violation
             Map<String, String> responseObj = new HashMap<String, String>();
             responseObj.put("email","Email taken");
             builder = Response.status(Response.Status.CONFLICT).entity(responseObj);


    If the member is not valid them a map is created that contains the field name with the error, and the error message associated with that error from Bean Validation.  It is also very important to set the response code correctly.  In our case with use 400 BAD REQUEST for standard constraints, and 409 CONFLICT is another member already has the same email.


    If the member is valid the object is committed to the database and a CDI event is triggered just in case anything in the application wanted to know when a new member was created.  The method then returns a standard HTTP 200 OK message using the Response.OK() method.


             //Register the member
   "Registering " + member.getName());
             //Trigger the creation event
             //Create an "ok" response
             builder = Response.ok();


    Github Source:


    The JaxRsActivator class does two things for us.  First is initializes JAX-RS without the need of a web.xml file, and second it defined the root path for all other JAX-RS HTTP call like this:


    public class JaxRsActivator extends Application {
       /* class body intentionally left blank */


    Github Source:


    The Resources class uses CDI to alias Java EE resources, such as the persistence context, to CDI beans.  This makes them available to all other CDI beans, ala

    Testing the Application Code

    Testing an HTML5 based application requires some addition considerations.  First you need to test the JAX-RS  back end services.  Second with more logic existing in JavaScript you need an effective way of unit testing that.


    We cover that in another article: Testing HTML5 Mobile Quickstart & Archetype