In SPRINGMVC, the controller returns JSON data in two ways, 1.jsp Ajax requests:
function Getjson () { $.ajax ({ type:"get", DataType:"JSON", URL:"<%= BasePath%>getjson ", success:function(data) { for(var i=0;i<jsondata.length;i++) { alert ("Id:" +data[i].id+ " Username:" +data[i]. username); } },
Error:function (e) {
Alert (e);
} })}
2. Method One: Use SPRINGMVC native annotations @responsebody
@ResponseBody @RequestMapping ("/getjson") public Object Getjson () { return new Object (); }
Attention:
[Email protected] Function: The return value of the target method is automatically converted to JSON format, and then returned to the front end 3. Method Two:
Using the JSON tool class for manual writing
@RequestMapping ("/getjson") publicvoid Getjson (httpservletresponse Response) {
Object obj = new Object ();
= Jsonobject.fromobject (obj); Jsonutils.ajaxjson (json.tostring (), response); }
Attach the code for the Jsonutils tool class:
Importjava.io.IOException;ImportJavax.servlet.http.HttpServletResponse; Public classJsonutils { Public Static voidAjaxjson (String jsonstring,httpservletresponse response) {Ajax (jsonstring,"Application/json", response); } Public Static voidAjax (String content, string Type,httpservletresponse response) {Try{response.setcontenttype (type+ "; Charset=utf-8"); Response.setheader ("Pragma", "No-cache"); Response.setheader ("Cache-control", "No-cache"); Response.setdateheader ("Expires", 0); Response.getwriter (). write (content); Response.getwriter (). Flush (); } Catch(IOException e) {e.printstacktrace (); } }}
Two ways controller returns JSON data in SPRINGMVC