As a part of our Free Dojo Support initiative, we received the following question about using the new dojo.store.JsonRest API with Spring:

The Question

There are no examples of the server-side of the new dojo.store.JsonRest APIs using spring. There are a few detailing the older dojox.data interfaces, but nothing combining the latest dojo.store with annotated spring controllers. This would be a good jump off point for any new app given the prevalence of both of these technologies.

The Answer

To answer this question, we discussed this with Jeremy Grelle at vmware/Spring, who was nice enough to put together an example using dojo.store.JsonRest with Spring on GitHub.

There is a Spring @MVC controller backing the JsonRest store and a simple US States demo page.

The readme file contains complete details on how to make this work, and also notes a couple of current limitations between the dojo.store.JsonRest API and Spring, which will be addressed in the near future.

The example is reasonably self-explanatory. The client-side portion of the code is concise. Just create a store, add a caching wrapper, target the URL of the usstates service, create a grid, connect it to the store, define the structure for displaying data in the grid, bind it to a node, render the grid, and then connect save events to the save command on the store:

myStore = dojo.store.Cache(
	dojo.store.JsonRest({target:"usstates/"}),
	dojo.store.Memory());
grid = new dojox.grid.DataGrid({
	store: dataStore = dojo.data.ObjectStore({
		objectStore: myStore}),
	structure: [
		{name:"State Name", field:"name", width: "200px"},
		{name:"Abbreviation", field:"abbreviation",
			width: "200px", editable: true}
	]
	// make sure you have a target HTML element with this id
	}, "target-node-id");
grid.startup();
dojo.query("#save").onclick(function(){
dataStore.save();
});

The server-side code is also to the point. After including the necessary modules, you connect a Spring Roo WebScaffold as the URL path available to the client-side store, to the USState for backing class. You then map the URL to an HTTPRequest, define HTTP settings for the controller object to deliver JSON, etc., and then define various methods for delivering a response based on the request type (GET/PUT/POST/DELETE, etc.), and available data. Finally there are helper methods to support server-side sorting, and requesting data in blocks to support pagination of data loading:

@RooWebScaffold(
	path = "usstates", formBackingObject = USState.class)
@RequestMapping("/usstates")
@Controller
public class USStateController {    
    private static final String RANGE_PREFIX = "items=";
    private static final String CONTENT_RANGE_HEADER = "Content-Range";
    private static final String ACCEPT_JSON = "Accept=application/json";
    @RequestMapping(value="/{id}", method=RequestMethod.GET, headers=ACCEPT_JSON)

    public @ResponseBody USState getJson(@PathVariable("id") Long id) {
        return USState.findUSState(id);
    }
    
    /**
* TODO - Should probably be stricter here in following the HTTP spec,
* i.e. returning the proper 20x response instead of an explicit redirect
*/
    @RequestMapping(method=RequestMethod.POST, headers=ACCEPT_JSON)
    public String createJson(@Valid @RequestBody USState state) {
        state.persist();
        return "redirect:/usstates/"+state.getId();
    }
    
    @RequestMapping(value="/{id}", method={RequestMethod.POST, RequestMethod.PUT}, headers={ACCEPT_JSON,"If-None-Match=*"})
    public String createJsonWithId(@Valid @RequestBody USState state, @PathVariable("id") Long id) {
        Assert.isTrue(USState.findUSState(id) == null);
        return updateJson(state, id);
    }
    
    @RequestMapping(value="/{id}", method={RequestMethod.POST, RequestMethod.PUT}, headers={ACCEPT_JSON,"If-Match=*"})
    public String overWriteJson(@Valid @RequestBody USState state, @PathVariable("id") Long id) {
        Assert.isTrue(USState.findUSState(id) != null);
        return updateJson(state, id);
    }
    
    /**
* TODO - Should probably be stricter here in following the HTTP spec,
* i.e. returning the proper 20x response instead of an automatic redirect
*/
    @RequestMapping(value="/{id}", method=RequestMethod.PUT, headers=ACCEPT_JSON)
    public String updateJson(@Valid @RequestBody USState state, @PathVariable("id") Long id) {
        Assert.isTrue(id.equals(state.getId()));
        state.merge();
        return "redirect:/usstates/"+state.getId();
    }
    
    @RequestMapping(method=RequestMethod.DELETE, headers=ACCEPT_JSON)
    public @ResponseBody ResponseEntity<String> deleteJson(@PathVariable("id") Long id) {
        USState.findUSState(id).remove();
        return new ResponseEntity<String>(HttpStatus.NO_CONTENT);
    }
    
    @RequestMapping(method=RequestMethod.GET, headers=ACCEPT_JSON)
    public @ResponseBody HttpEntity<List<USState>> listJson() {
        HttpHeaders headers = new HttpHeaders();
        List<USState> body = null;
        body = USState.findAllUSStates();
        headers.add(CONTENT_RANGE_HEADER, getContentRangeValue(0, body.size(), new Integer(body.size()).longValue()));
        return new HttpEntity<List<USState>>(body, headers);
    }
    
    @RequestMapping(method=RequestMethod.GET, headers={ACCEPT_JSON, "Range"})
    public @ResponseBody HttpEntity<List<USState>> listJsonForRange(@RequestHeader(value="Range") String range, HttpServletRequest request) {
        HttpHeaders headers = new HttpHeaders();
        List<USState> body = null;
        Range parsedRange = new Range(range.replaceAll(RANGE_PREFIX, ""));
        long count = USState.countUSStates();
        body = USState.findUSStateEntries(parsedRange.getFirstResult(), parsedRange.getMaxResults());
        headers.add(CONTENT_RANGE_HEADER, getContentRangeValue(parsedRange.getFirstResult(), body.size(), count));
        return new HttpEntity<List<USState>>(body, headers);
    }
    
    /**
* TODO - This doesn't actually get selected since the query param is in the form of 'sort(...)' instead of 'sort=(...)'
*/
    @RequestMapping(method=RequestMethod.GET, headers={ACCEPT_JSON, "Range"}, params="sort")
    public @ResponseBody HttpEntity<List<USState>> listJsonForRangeSorted(@RequestHeader("Range") String range, @RequestParam("sort") String sort) {
        HttpHeaders headers = new HttpHeaders();
        List<USState> body = null;
        Range parsedRange = new Range(range.replaceAll(RANGE_PREFIX, ""));
        long count = USState.countUSStates();
        //TODO - Implement sort param parsing
        body = USState.findOrderedUSStateEntries(parsedRange.getFirstResult(), parsedRange.getMaxResults(), "");
        headers.add(CONTENT_RANGE_HEADER, getContentRangeValue(parsedRange.getFirstResult(), body.size(), count));
        return new HttpEntity<List<USState>>(body, headers);
    }
    
    private String getContentRangeValue(Integer firstResult, Integer resultCount, Long totalCount) {
        StringBuilder value = new StringBuilder("items "+firstResult+"-");
        if (resultCount == 0) {
            value.append("0");
        } else {
            value.append(firstResult + resultCount - 1);
        }
        value.append("/"+totalCount);
        return value.toString();
    }
    
    private static final class Range {
        
        private Integer firstResult = 0;
        private Integer maxResults = 0;
        
        public Range(String range) {
            String[] parsed = range.split("-");
            Assert.isTrue(parsed.length == 2, "Range header in an unexpected format.");
            this.firstResult = new Integer(parsed[0]);
            Integer end = new Integer(parsed[1]);
            this.maxResults = end - firstResult + 1;
        }
        
        public Integer getFirstResult() {
            return this.firstResult;
        }
        
        public Integer getMaxResults() {
            return this.maxResults;
        }
    }
    
}

Next Question Please!

Have a Dojo question you’re just dying to ask? Get your free Dojo support now! Or sign-up for the Best JavaScript and Dojo Support available to get all of your questions answered all the time!