

Introduction

This is an introductory tutorial for Java web developers who are new to the Dojo Grid component. This tutorial shows you how to populate a grid component with data retrieved from a servlet in the JavaScrip Object Notation (JSON) format. This tutorial displays a grid with a list of roleplaying games (RPG). Here is a screenshot of the grid you will build in this tutorial:

Know the Grid

Grids in dojo are defined based on a structure and a model. The structure is used to specify the type of data to be displayed, its format, position and how it is being displayed. The model on the other hand holds the actual data that you get from the server.

The Structure

From the book of dojo: “In the world of Grid, the structure is the largest unit. Structures are composed of views. Views are composed of cells.” This is nice and simple, however, you often need to combine a number of cells into a row. You might also need to group rows into one giant row that can be selected.

// a view can be composed of a single cell var rowBarView = {type: 'dojox.GridRowView', width: '20px'}; // a subrow is composed of a number of cells var subrow = [ {name:'Title',field:'title', width: "300px"}, {name:'Developer',field:'developer', width: "150px"}, {name:'Score',field:'score', width: "75px"} ]; var subrow2 = [ {name:'Platform', field:'platform', width: "300px"}, {name:'Release Date',field:'releaseDate', width: "150px"} ]; // one or more subrows can be grouped into a view // the grouping of subrows forms a single selectable row var contentView = { rows: [subrow, subrow2] }; // a structure is composed of views var gridStructure = [ rowBarView, contentView ];

In dojo terminology a row combining a number of cells is a subrow while the combination of the subrows forms the selectable row. Line 02 above defines a simple view with a single cell. The cell has a width of 20 pixels and is of type dojox.GridRowView which provides a selectable region for grid rows. Lines 04 through 14 define the cells holding your data. Each cell has a name used as a header and a field attribute that defines the mapping of the data with the model defined below. The two subrows are combined into a view called contentView so that they can be selected and highlighted at the same time. Finally, you define an array of views as the structure of your grid.

The Model

A model is an object that holds data in a format the grid can understand. In dojo you get the data from a data source, a servlet in this case, using a data store. Data stores are JavaScript objects that can get data from different sources such as arrays, files, and databases. After getting the data you use a model which acts as the point of interaction between the grid and the data store. Performing operations related to data retrieval and manipulation are done using the model. For example, you can set a query on the model to limit the amount of data retrieved from the back-end.

Define the Grid

To have a grid component you need to define three div tags with the required dojoType attribute. You also need to set the jsId attribute to define the associations between the tags.

The first tag defines your data store, the data source and the http method to use. Lines 02 and 03 below define a data store of type QueryReadStore that can be used to send query parameters to the data source. The url parameter specifies the address of the servlet to get data from, it is the same value defined in the url-pattern defined under the servlet-mapping tag in web.xml. You can also specify the HTTP method to use for the request.

The second tag of type DojoData is used to define the model of the grid. It has a number of useful parameters that can be set to perform operations locally using JavaScript such as sorting. You may also use the query attribute to specify some parameters to send to the data source as show in Line 08.

The third tag defines the grid as show in lines 11 and 12. To have the grid populated you need to specify the set the values of the structure and the model attributes.

<!-- Data stores read data from a data store such as a servlet --> <div dojoType="dojox.data.QueryReadStore" jsId="store" url="GameDataProvider" requestMethod="get"></div> <!-- A model is the point of interaction between the grid and the data store --> <div dojoType="dojox.grid.data.DojoData" jsId="model" clientSort="true" rowsPerPage="20" store="store" query="{genre: 'Traditional RPG'}"></div> <!-- A grid displays data and offer useful operations such as client sorting --> <div autoWidth="true" autoHeight="true" dojoType="dojox.Grid" model="model" structure="gridStructure" jsId="gridWidget"></div>

The RolePlayingGame Class

This is a simple JavaBean class with some properties and a toJSONObject method that returns a String representation of the object in JSON format.

import org.json.JSONException; import org.json.JSONObject; public class RolePlayingGame { private String title; private String developer; private Date releaseDate; private int score; private Platform platform; private transient SimpleDateFormat dateFormatter; public RolePlayingGame(){ dateFormatter = new SimpleDateFormat("dd MMMM, yyyy"); } // getters and setter omitted public JSONObject toJSONObject() { JSONObject json = new JSONObject(); try { json.put("title", title); json.put("developer", developer); json.put("releaseDate", dateFormatter.format(releaseDate)); json.put("score", score); json.put("platform", platform.value()); } catch (JSONException e) { e.printStackTrace(); } return json; } }

The RolePlayingGame class uses the JSONObject class from the json.org library to create a json object. The created json object can be easily returned as a string as shown in the code below. The order you put the properties in the json object is not important since the JSONObject class uses a HashMap internally to store them.

{"platform":"PlayStation 2","title":"Persona 3: FES","releaseDate":"19 April, 2007","developer":"Atlus","score":98}

Sending Data using a Servlet

To send data back to dojo you simply need to get a string in JSON format of the RPGs you want to display on the grid. In this tutorial, the getSampleGames method defined in line 31 constructs the list of RPGs and add them to an instance of JSONArray. Note that you need to call the toJSONObject object on each object before adding it to the json array as shown in lines 44 and 53. After adding all the RPGs to the json array you need to add it to an instance of JSONObject under the name items, use a different name and your grid will not display any data.

The body of the doPost method is simple as it calls the toString method on the json object returned by the getSampleGames method and writes it back to the browser.

import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class GameDataProvider extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { public GameDataProvider() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // print out the parameters sent from Dojo Enumeration e = request.getParameterNames(); while(e.hasMoreElements()){ String name = e.nextElement().toString(); System.out.println("name: "+name+" value: "+request.getParameter(name)); } response.setContentType("text/plain"); response.getWriter().write(getSampleGames().toString()); response.getWriter().flush(); response.getWriter().close(); } private JSONObject getSampleGames(){ JSONObject json = new JSONObject(); JSONArray games = new JSONArray(); GregorianCalendar gc = new GregorianCalendar(); RolePlayingGame game = new RolePlayingGame(); game.setTitle("Persona 3: FES"); game.setDeveloper("Atlus"); gc.set(2007, Calendar.APRIL, 19); game.setReleaseDate(gc.getTime()); game.setScore(98); game.setPlatform(Platform.PLAYSTATION2); games.put(game.toJSONObject()); game = new RolePlayingGame(); game.setTitle("Shin Megami Tensei: Digital Devil Saga");; game.setDeveloper("Atlus R&D1"); gc.set(2004, Calendar.JULY, 15); game.setReleaseDate(gc.getTime()); game.setScore(93); game.setPlatform(Platform.PLAYSTATION2); games.put(game.toJSONObject()); try{ // The attribute name has to be items, using games does not work json.put("items", games); // json.put("games", games); }catch(JSONException e){ e.printStackTrace(); } return json; } }

You need to define your servlet in web.xml and give it the value GameDataProvider so that the QueryReadStore can access it.

<servlet> <servlet-name>GameDataProvider</servlet-name> <servlet-class>com.osplayground.dojo.GameDataProvider</servlet-class> </servlet> <servlet-mapping> <servlet-name>GameDataProvider</servlet-name> <url-pattern>/GameDataProvider</url-pattern> </servlet-mapping>

That’s it, you now have simple grid accessing a servlet to display a list of roleplaying games. The source codes are attached below.

Attachments

When saving the attachments remove the .odt extention and replace the last underscore with a dot. For example videogames_sample_html.odt should be saved as videogames_sample.html. This is due to the limitation in uploading sources files and text documetn in wordpress.com.

Resources