Ajax asynchronous request JSON format data _ajax related in SPRINGMVC environment

Source: Internet
Author: User
Tags current time i18n json xmlns

An environment to build

The first is a regular spring MVC environment, and needless to say, it needs to be noted that you need to introduce the Jackson-related jar package and then add the JSON resolution-related configuration in the Spring configuration file "Springmvc-servlet.xml". My complete code here is as follows:

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" 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 "> <!--to prevent IE from executing AJAX, return JSON to appear download files-- > <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 the annotation function of spring MVC, complete the mapping of request and annotation Pojo--> <bean class= " Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter "> <property name="
Messageconverters "> <list> <ref bean=" Mappingjacksonhttpmessageconverter "/><!--JSON converter--> </list> </property> </bean> <mvc:annotation-driven content-negotiation-manager= " Contentnegotiationmanager "/> <bean id=" Contentnegotiationmanager "class="
Org.springframework.web.accept.ContentNegotiationManagerFactoryBean "> <!--true, turn on extension support, false close support--> <property name= "Favorpathextension" value= "false"/> <!--Support for opening/userinfo/123?format=json--> <property name= "Favorparameter" value= "true"/> <!-- Set to true to ignore support for the Accept header--> <property name= "Ignoreacceptheader" value= "false"/> <property " MediaTypes "> <value> atom=application/atom+xml html=text/html json=application/json xml=application/xml *=* /* </value> </property> </bean> <context:annotation-config/> <!--start automatically scan all the beans under the package ( For example @controller)--> <context:component-scan base-package= "Cn.zifangsky.controller"/> <mvc: Default-servlet-handler/> <!--definition View parser--> <bean id= "Jspviewresolver" 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:

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

Two test examples

(1) A new index.jsp file is created in the web-inf/jsp directory, containing a simple jquery Ajax request, and the format of the request data is JSON, 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, the code is as follows:

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 * * * @RequestM Apping (value = "/hello.json", method = {Requestmethod.post}) @ResponseBody public map<string, string> hello (@Reque Stbody User User {//returns the MAP set map<string of the data, string> result= new hashmap<string, string> ();
Format format = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
Returns the requested username Result.put ("username", user.getusername ());
Returns the Age Result.put ("Ages", String.valueof (User.getage ()));
Returns the current result.put ("Time", Format.format (New Date ());
return result; }
}

For a specific implementation step, let me briefly say:

i) after the project starts, it is accessed in the browser: http://localhost:8089/SpringDemo/hello.html, then goes to the list method in the execution controller, and then goes to/web-inf/jsp/ Index.jsp (PS: A logical view is returned in controller, and the true path of the composite file is spliced with the path prefix and suffix defined in the Springmvc-servlet.xml file)

II Enter text on the index.jsp page and click on the button, which will trigger the AJAX request, which will get the data in the input box and the default "age" parameter to be spliced into the JSON format string and finally submit to the "Hello.json" request, Which is the Hello method in the execution controller

III) The Hello method returns a series of data after execution and finally appears in the page

(4) The effect is as follows:

The above is a small set to introduce the SPRINGMVC environment in the implementation of AJAX asynchronous request JSON format data related content, I hope to help!

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.