Ajax asynchronous requests implemented in SPRINGMVC environments (JSON format data)

Source: Internet
Author: User
Tags i18n

An environment construction

The first is the regular spring MVC environment build, needless to say, it is important to note that the Jackson related jar package needs to be introduced, and then add JSON parsing related configuration in spring config file "Springmvc-servlet.xml" , my complete code here is as follows:

<?xml version= "1.0"  encoding= "UTF-8"? ><beans xmlns= "http://www.springframework.org/ Schema/beans "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance " xmlns:context="/HTTP/ Www.springframework.org/schema/context "xmlns:mvc=" Http://www.springframework.org/schema/mvc "xsi:schemalocation = "http://www.springframework.org/schema/beans    http://www.springframework.org/schema/ beans/spring-beans-4.0.xsd       http://www.springframework.org/schema/ context        http://www.springframework.org/schema/context/ Spring-context-4.0.xsd       http://www.springframework.org/schema/mvc         http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd " ><!--  Avoid IE when performing Ajax, return json appears download file  --><bean id= "Mappingjacksonhttpmessageconverter" Class= "Org.springframework.http.converter.json.MappingJAcksonhttpmessageconverter "><property name=" Supportedmediatypes "><list><value>text/ html;charset=utf-8</value><value>application/json;charset=utf-8</value></list></ Property><property name= "Objectmapper" ><bean class= " Org.codehaus.jackson.map.ObjectMapper "><property name=" DateFormat "><bean class=" Java.text.SimpleDateFormat "><constructor-arg type=" java.lang.String " value=" yyyy-mm-dd hh : Mm:ss "></constructor-arg></bean></property></bean></property></bean> <!--  start SPRING&NBSP;MVC annotation function, complete the mapping of request and annotation Pojo  --><beanclass= " Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter "><property name=" Messageconverters "><list><ref bean=" Mappingjacksonhttpmessageconverter " /><!--  json Converter  --></list></property></bean><mvc:annotation-drivencontent-Negotiation-manager= "Contentnegotiationmanager"  /><bean id= "Contentnegotiationmanager" class= " Org.springframework.web.accept.ContentNegotiationManagerFactoryBean "><!-- true, turn on extension support, false turn off support  --><property name= "Favorpathextension"  value= "false"  /><!--  to enable  / Userinfo/123?format=json support  --><property name= "Favorparameter"  value= "true"  /> <!--  Set to true to ignore support for Accept header  --><property name= "Ignoreacceptheader"   Value= "false"  /><property name= "MediaTypes" ><value>atom=application/atom+xmlhtml=text /htmljson=application/jsonxml=application/xml*=*/*</value></property></bean><context: annotation-config /><!--  Start automatically scans all beans under the package (e.g. @controller)  --><context:component-scan  base-package= "Cn.zifangsky.controller"  /><mvc:default-servlet-handler /><!--  Defining the View resolver  --><beaN id= "Jspviewresolver" class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" >< Property name= "Requestcontextattribute"  value= "RC"  /><property name= "ViewClass" value = "Org.springframework.web.servlet.view.JstlView"  /><property name= "prefix"  value= "/ web-inf/jsp/" /><property name=" suffix " value=". jsp " /><property name=" Order " value=" 1 "></property></bean></beans>

Project structure:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/7F/6C/wKioL1ceL1_RzTmBAAA1S10S6x0204.png "title=" 20160407180921_91582.png "alt=" Wkiol1cel1_rztmbaaa1s10s6x0204.png "/>


Note: I test the full jar package used here: Http://pan.baidu.com/s/1dEUwdmL

For reference only


Two test examples

(1) A new index.jsp file is created in the web-inf/jsp directory, which contains the simple jquery Ajax request, the format of the request data is JSON, the specific code is as follows:

<%@ page language= "java"  contenttype= "Text/html; charset=utf-8" pageEncoding= "UTF-8"% ><%string path = request.getcontextpath (); String basepath = request.getscheme ()  +  "://"  + request.getservername ()  +  ":"  + request.getserverport () + path +  "/";%>

(2) a simple model class user with the following code:

package cn.zifangsky.controller;public class user { Private string username;private int age;public string getusername ()  {return  username;} Public void setusername (String username)  {this.username = username;} Public int getage ()  {return age;} Public void setage (Int age)  {this.age = age;}} 

(3) Controller class Testcontroller.java:

package cn.zifangsky.controller;import java.text.format;import java.text.simpledateformat; import java.util.date;import java.util.hashmap;import java.util.map;import  Org.springframework.context.annotation.scope;import org.springframework.stereotype.controller;import  org.springframework.web.bind.annotation.RequestBody;import  org.springframework.web.bind.annotation.requestmapping;import  org.springframework.web.bind.annotation.requestmethod;import  org.springframework.web.bind.annotation.responsebody;import org.springframework.web.servlet.modelandview; @Controller @scope ("prototype") public class testcontroller {/** *  go to page  */@ Requestmapping (value =  "/hello.html") public modelandview list ()  {ModelAndView  View = new modelandview ("index"); Return view;} /** * ajax asynchronous request,  request format is json */@RequestMapping (value =  "/hello.json",  metHOD&NBSP;=&NBSP;{&NBSP;REQUESTMETHOD.POST&NBSP,}) @ResponseBodypublic  Map<String, String>  Hello (@RequestBody  user user)  {//  Map Collection of returned data Map<string, string> result  = new HashMap<String, String> (); Format format = new simpledateformat ("Yyyy-mm-dd hh:mm:ss");//  Returns the requested Usernameresult.put ("username",  user.getusername ());//  returns the Age Result.put ("ages",  string.valueof (User.getage ())); /  returns the current time Result.put ("Times",  format.format (New date ())); return result;}}

For specific implementation steps I would simply say:


i) after the project is started, Access: http://localhost:8089/SpringDemo/hello.html in the browser, then go to the list method in the execution controller, then go to/web-inf/jsp/ Index.jsp (PS: The logical view is returned in the controller, followed by the path prefix and suffix defined in the Springmvc-servlet.xml file to synthesize the true path of the file)


II) Enter text on the index.jsp page and click on the button, will trigger the AJAX request, this request will get the input box data and the default "age" parameter stitching into a JSON format string last submitted to "Hello.json" this request, That is, the Hello method in the controller is executed


iii) After execution of the Hello method, a series of data is returned and finally displayed in the page




(4) The effect is as follows:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/7F/6E/wKiom1ceLxKTLKMqAABmEB8LihM051.png "title=" 20160407182528_39114.png "alt=" Wkiom1celxktlkmqaabmeb8lihm051.png "/>


This article is from "Zifangsky's personal blog" blog, make sure to keep this source http://983836259.blog.51cto.com/7311475/1767692

Ajax asynchronous requests implemented in SPRINGMVC environments (JSON format data)

Related Article

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.