I am looking to retrieve JSON data from a Spring controller using JavaScript. Below is the REST API call that returns the JSON data:
{id: '0', item: [
{
id: 'all',
text: 'ALL',
item: [
{
id: 'all-',
text: 'ALL-',
item: [
{
id: 'Market1-0',
text: 'Market1',
item: [
{
id: 'id2',
text: 'Project 2'
},
{
id: 'id1',
text: 'Project 1'
}
]
}
]
}
]
}
]
}
Here is the code for the Spring handler:
public class DashboardHandler {
public String getProjects() throws ParseException{
SimpleClientHttpRequestFactory rf = new SimpleClientHttpRequestFactory();
rf.setReadTimeout(50000);
rf.setConnectTimeout(50000);
RestTemplate restTemplate = new RestTemplate(rf);
String page = restTemplate.getForObject(
"http://localhost:9090/mcps/api/v1.0/user/2/projects",
String.class);
// Parsing the JSON response
JSONParser parser = new JSONParser();
JSONObject customerListObject = (JSONObject) parser.parse(page);
// Building the JSON object
StringBuilder builder = new StringBuilder();
builder.append("{id:'0', item:[");
builder.append("{id:'all', text:'ALL', item:[");
int i=0;
for (Object customer : customerListObject.keySet()) {
JSONObject customerJsonObject = (JSONObject) customerListObject
.get(customer.toString());
for (Object region : customerJsonObject.keySet()) {
JSONObject marketJsonObject = (JSONObject) customerJsonObject
.get(region.toString());
for (Object market : marketJsonObject.keySet()) {
builder.append("{id:'"+market+"-"+i+"', text:'"+market+"', item:[");
i++;
JSONObject projectObject = (JSONObject) marketJsonObject
.get(market.toString());
for(Object projectId:projectObject.keySet()){
JSONObject projectJsonObject = (JSONObject) projectObject.get(projectId);
for(Object project: projectJsonObject.keySet()){
builder.append("{id:'"+projectId+"', text:'"+project+"'},");
}
}
builder.append("]},");
}
}
}
builder.append("]}]}");
return builder.toString();
}
}
The controller with request mapping URL is as follows:
@Controller
public class DashboardController {
@RequestMapping(value = "/getProjects", method = RequestMethod.GET)
public @ResponseBody String getProjects(HttpServletRequest request) {
DashboardHandler dashBoardHandler = new DashboardHandler();
try {
return dashBoardHandler.getProjects();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
Now, I want to know how to access the /getProjects URL in JavaScript. Can anyone help me with this?