本篇文章講述對JSON數據的處理,關於響應的處理能夠看我第二篇文章
連接地址:https://segmentfault.com/a/11...javascript
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:ApplicationContext.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>mvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
<?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:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 開啓spring註解驅動--> <context:component-scan base-package="com.cjh"/> <!-- 開啓mvc註解驅動--> <mvc:annotation-driven></mvc:annotation-driven> </beans>
點擊button,發送JSON數據html
<%@ page contentType="text/html; charset=UTF-8" language="java" %> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>cai jin hong</title> <script type="text/javascript"> window.onload = function () { document.getElementById("button").onclick = function () { //一、建立一個AJAX對象 var xhr = new XMLHttpRequest(); xhr.open("POST", "test.do", true); //告知瀏覽器發送的是什麼信息 xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8"); //二、隨時監聽響應回來的數據 xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200){ alert(xhr.responseText); } } //三、發送JSON數據 xhr.send('{"account":"2020", "password": "123456", "balance":98}'); } } </script> </head> <body> <button id="button">測試JSON數據</button> </body> </html>
@Controller public class UserController { //方法中傳入實體對象:對象裏面有list集合 @RequestMapping("test.do") public void testFive(@RequestBody User user){ System.out.println(user); } }
響應實體對象:使用@ResponseBody註解,直接返回實體對象(mvc會把它轉換成JSON格式的數據)java
@Controller public class UserController { //方法中傳入實體對象:對象裏面有list集合 @RequestMapping("test.do") @ResponseBody public User testFive(User user){ System.out.println(user); return user; } }