I hava a JAVA EE backend and I am using Spring MVC. I have a AJAX call like this:
function getAllProjects() {
$.getJSON("project/getall", function(allProjects) {
???
});
}
My backend system:
@RequestMapping(value="/getall", method=RequestMethod.GET)
public @ResponseBody ??? getAllProjects() {
???
}
What is the content I have to implement so it will work? In the backend system I have from a database call the unique id and the name of the project, for example:
1 => My Test Project
4 => Another One
23 => One More Test
The id and the project name should be returned to the frontend system, so I can build a HTML ul/li list in this kind:
<ul>
<li><a href="/1">My Test Project</a></li>
<li><a href="/4">Another One</a></li>
<li><a href="/23">One More Test</a></li>
</ul>
Does anyone know how this can be done?
To return JSON from the server, you must include the JSON data in the body of the HTTP response message and provide a "Content-Type: application/json" response header. The Content-Type response header allows the client to interpret the data in the response body correctly.
Send JSON Data in POST Spring provides a straightforward way to send JSON data via POST requests. The built-in @RequestBody annotation can automatically deserialize the JSON data encapsulated in the request body into a particular model object. In general, we don't have to parse the request body ourselves.
You need to:
<mvc:annotation-driven>
to your configMap<Integer, String>
For more complex cases when you need to configure mapping process for each handler method you may use MappingJacksonJsonView
instead of @ResponseBody
, as Stepen C suggested.
You need to read Chapter 15.5 of the Spring User Guide which describes how to configure MVC views, and Chapter 16.10 which briefly describes the JSON Mapping View. Then read the javadocs for MappingJacksonJsonView
etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With