Ajax asynchronous request in SpringMVC environment in JSON format, springmvcjson

Source: Internet
Author: User
Tags i18n

Ajax asynchronous request in SpringMVC environment in JSON format, springmvcjson

Environment 1

First of all is the establishment of the General spring mvc environment, needless to say, it should be noted that here you need to introduce jackson related jar package, and then add json parsing related configuration in the spring configuration file "springmvc-servlet.xml, the 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 "> <! -- When IE executes AJAX, the downloaded file is returned in JSON --> <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> <! -- Start the annotation function of Spring MVC to map requests 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: enable extension support, and disable extension support by false --> <property name = "favorPathExtension" value = "false"/> <! -- Is used to enable/userinfo/123? Format = json support --> <property name = "favorParameter" value = "true"/> <! -- Set true to ignore support for Accept headers --> <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 to automatically scan all beans under the package (for example, @ Controller) --> <context: component-scan base-package = "cn. zifangsky. controller "/> <mvc: default-servlet-handler/> <! -- Define view parser --> <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:

Note: The complete jar package I tested here: http://pan.baidu.com/s/1dEUwdmL

2. Test instance

(1) In the WEB-INF/jsp directory to create a new index. jsp file, contains a simple jQuery ajax request, the request data format 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 the page */@ RequestMapping (value = "/hello.html") public ModelAndView list () {ModelAndView view = new ModelAndView ("index"); return view;}/*** ajax asynchronous request. The request format is json */@ RequestMapping (value = "/hello. json ", method = {RequestMethod. POST}) @ ResponseBodypublic Map <String, String> hello (@ RequestBody User user) {// Map set 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 ("age", String. valueOf (user. getAge (); // returns the result of the current time. put ("time", format. format (new Date (); return result ;}}

Let me briefly describe the specific steps:

(I) after the project is started, access http: // localhost: 8089/SpringDemo/hello.html in the browser, and then go to the list Method in the controller to execute, then go to/WEB-INF/jsp/index. jsp (PS: the logical view returned in the controller, with the path prefix and suffix defined in the springmvc-servlet.xml file after splicing the true path of the file)

Ii) In index. enter text on the jsp page and click the button to trigger the ajax request. This request obtains the data in the input box and Concatenates the default "age" parameter into a json string and finally submits it to "hello. json "request, that is, execute the hello method in the controller.

Iii) after the hello method is executed, a series of data is returned and displayed on the page.

(4) The effect is as follows:

The above section describes the content of Ajax asynchronous request in JSON format in SpringMVC. I hope it will help you!

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.