


Ajax asynchronous request for JSON format data implemented in SpringMVC environment
This article mainly introduces the relevant information of Ajax asynchronous request for JSON format data implemented in the SpringMVC environment. Friends who need it can refer to it
One environment construction
The first is the conventional spring mvc environment setup. Needless to say, it should be noted that the jackson related jar package needs to be introduced here, and then the json parsing related information is added to the spring configuration file "springmvc-servlet.xml" Configuration, 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"> <!-- 避免IE执行AJAX时,返回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> </property> </bean> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 --> </list> </property> </bean> <mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" /> <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"> <!-- true,开启扩展名支持,false关闭支持 --> <property name="favorPathExtension" value="false" /> <!-- 用于开启 /userinfo/123?format=json的支持 --> <property name="favorParameter" value="true" /> <!-- 设置为true以忽略对Accept Header的支持 --> <property name="ignoreAcceptHeader" value="false" /> <property name="mediaTypes"> <value> atom=application/atom+xml html=text/html json=application/json xml=application/xml *=*/* </value> </property> </bean> <context:annotation-config /> <!-- 启动自动扫描该包下所有的Bean(例如@Controller) --> <context:component-scan base-package="cn.zifangsky.controller" /> <mvc:default-servlet-handler /> <!-- 定义视图解析器 --> <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:
##Two test examples
(1) Create a new index.jsp file in the WEB-INF/jsp directory, which contains a 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 + "/"; %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <base href="<%=basePath%>"> <script type="text/javascript" src="scripts/jquery/jquery-1.6.2.min.js"></script> <script type="text/javascript" src="scripts/jquery/jquery.i18n.properties-min-1.0.9.js"></script> <script type="text/javascript" src="scripts/jquery/jquery.autocomplete.js"></script> <script type="text/javascript" src="scripts/jquery/jquery.loadmask.js"></script> <script type="text/javascript" src="scripts/jquery/jquery.form.js"></script> <script type="text/javascript" src="scripts/jquery/jquery.timers.js"></script> <title>jQuery i18n</title> <script type="text/javascript"> $().ready( function() { $("#sub").click( function() { var name = $("#username").val(); var age = 18; var user = {"username":name,"age":age}; $.ajax({ url : 'hello.json', type : 'POST', data : JSON.stringify(user), // Request body contentType : 'application/json; charset=utf-8', dataType : 'json', success : function(response) { //请求成功 alert("你好" + response.username + "[" + response.age + "],当前时间是:" + response.time + ",欢迎访问:http://www.zifangsky.cn"); }, error : function(msg) { alert(msg); } }); }); }); </script> </head> <body> <input type="text" id="username" style="width: 100px; height: 30px; font-size: 20px; font-weight: bold;"> <input type="button" id="sub" value="Go" style="height: 40px; height: 30px;"> <br> </body> </html>(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 { /** * 转到页面 */ @RequestMapping(value = "/hello.html") public ModelAndView list() { ModelAndView view = new ModelAndView("index"); return view; } /** * ajax异步请求, 请求格式是json */ @RequestMapping(value = "/hello.json", method = { RequestMethod.POST }) @ResponseBody public Map<String, String> hello(@RequestBody User user) { // 返回数据的Map集合 Map<String, String> result = new HashMap<String, String>(); Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 返回请求的username result.put("username", user.getUsername()); // 返回年龄 result.put("age", String.valueOf(user.getAge())); // 返回当前时间 result.put("time", format.format(new Date())); return result; } }Let me briefly talk about the specific execution steps:
i) After the project is started, visit: http://localhost:8089/SpringDemo/hello.html in the browser, then it will go to the list method in the controller, and then go to /WEB-INF/jsp /index.jsp (PS: The logical view returned in the controller is the real path of the file after being spliced with the path prefix and suffix defined in the springmvc-servlet.xml file) ii) In index Enter text on the .jsp page and click the button, which will trigger an ajax request. This request will get the data in the input box and the default "age" parameter, splice it into a json format string, and finally submit it to the "hello.json" request, that is Execute the hello method in the controlleriii) After the hello method is executed, a series of data will be returned and finally displayed on the page(4) The effect is as follows:
A brief discussion on ajax request technology
Ajax loading chrysanthemum loding effect
Very practical ajax user registration module
The above is the detailed content of Ajax asynchronous request for JSON format data implemented in SpringMVC environment. For more information, please follow other related articles on the PHP Chinese website!

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version
Chinese version, very easy to use

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
