Exposing JSON from a spring controller is surprisingly simple. In this episode I will create a controller that returns JSON and make a GET request from a client side template using jquery.
Detailed Video Notes
Project set up
Following our spring boot tutorial let us create a project using spring initializer web interface, selecting spring web and velocity as template engine. Lets start off by creating a
ContactController class. The controller is annotated with
@RestController which is a convenience annotation that combines the
Next creating a
@RequestMapping will expose an endpoint of
/contacts that will return JSON. We included additional meta data of
method which is a good practice that will allow spring to narrow down the mappings of the request. In other words, when DispatcherServlet accepts a request it will look at information in the request to determine where to route it. This would read, when a request is made to the application with an HTTP method of GET, a url of
/contacts and wanting JSON then spring will execute the
getContacts method. We will write a method to mock up some data but it could be substituted to connect to a database or a microservice. Firing up our server and making a request to
http://localhost:8080/contacts will convert the contacts arraylist to a jsonarray.
Once we have the REST URL returning JSON we need to create the template and render the view. Since
ContactController is annotated with
@RestController it will by pass processing the template and return the string directly to the response. We can fix this by either adding a new controller or changing the
@RestController to a
@Controller and adding the
@ResponseBody to the method we want to process JSON. For this example lets change
@Controller and add the
Adding mapping for template
We will then add the mapping that will resolve the template.
Creating the template
Lets run through the template at a high level. Binding a click event to the button and upon the event firing will execute the jquery get, a wrapper method for jquery ajax, that will getjson from
/contacts end point on our local server. Each contact returned from the successful response will be appended as a row to the tables with a class of
data-contacts-js. Finally importing bootstrap css and adding classes will add some presentation eye candy.
Making the GET request
Opening up chrome and developer tools console to inspect the network traffic we will making a request to
http://localhost:8080/view which will render the template successfully. Next clicking on the button will fire a request to our local server populating our table.
Thanks for joining in todays level up, have a great day.