Two ways controller returns JSON data in SPRINGMVC

Source: Internet
Author: User
Tags manual writing

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.