Spring MVC,JSON資料互動
阿新 • • 發佈:2021-10-05
一、前言
JSON(JavaScript Object Notation, JS 物件標記) 是一種輕量級的資料交換格式,採用完全獨立於程式語言的文字格式來儲存和表示資料。 易於閱讀和編寫,同時也易於機器解析和生成,並有效地提升網路傳輸效率。
通常前臺表單提交的資料主要有兩種格式,一種是jJSON格式的資料,另一種就是普通的key/value對,針對這兩種方式,在Controller類中會有不同的解析。
Spring MVC和前臺互動主要有兩種形式,如下圖所示:
上圖參考:https://blog.csdn.net/lch_2016/article/details/81022646
二、具體步驟
假定你已經具備開發環境,讀過前幾篇文章, 具體請參考:Spring MVC,繫結預設資料
步驟一、引用JSON包
SpringMVC預設用MappingJacksonHttpMessageConverter對JSON資料進行轉換,需要加入jackson包。包括:
- jackson-annotations-2.12.5.jar JSON轉換註解包
- jackson-core-2.12.5.jar JSON轉換核心包
- jackson-databind-2.12.5.jar JSON轉換的資料繫結包
步驟二、修改springmvc-config.xml
<?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.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 指定需要掃描的包 --> <context:component-scan base-package="com.itheima.controller" /> <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven> <!--配置靜態資源的訪問對映,此配置中的檔案,將不被前端控制器攔截 --> <mvc:resources location="/js/" mapping="/js/**" /> <!-- 定義檢視解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 設定字首 --> <property name="prefix" value="/WEB-INF/jsp/" /> <!-- 設定字尾 --> <property name="suffix" value=".jsp" /> </bean> </beans>
注意其中<mvc:resources />標籤。
步驟三、新建實體類
package com.itheima.po; /** * 使用者持久化類 */ public class User { private String username; // 使用者姓名 private String address; // 使用者地址 public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
四、新建表單jsonTest.jsp,位於:mvc目錄
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>測試JSON互動</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.11.3.min.js"> </script> <script type="text/javascript"> function testJson(){ // 獲取輸入的使用者名稱和地址 var username = $("#username").val(); var address = $("#address").val(); $.ajax({ url : "${pageContext.request.contextPath }/testJson", type : "post", // data表示傳送的資料 data :JSON.stringify({username:username,address:address}), // 定義傳送請求的資料格式為JSON字串 contentType : "application/json;charset=UTF-8", //定義回撥響應的資料格式為JSON字串,該屬性可以省略 dataType : "json", //成功響應的結果 success : function(data){ if(data != null){ alert("您輸入的使用者名稱為:"+data.username+ "地址為:"+data.address); } } }); } </script> </head> <body> <form> 使用者名稱:<input type="text" name="username" id="username"><br /> 地址: <input type="text" name="address" id="address"><br /> <input type="button" value="測試JSON互動" onclick=" testJson()" /> </form> </body> </html>
注意:本JSP引用jquery-1.11.3.min.js,請自行下載放置於JS目錄
步驟五、新建或修改控制器類
package com.itheima.controller; import java.util.List; 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.ResponseBody; import com.itheima.po.User; @Controller public class UserController { /** * 接收頁面請求的JSON資料,並返回JSON格式結果 */ @RequestMapping("/testJson") @ResponseBody public User testJson(@RequestBody User user) { // 列印接收的JSON格式資料 System.out.println(user); // 返回JSON格式的響應 return user; } }
UserController.java,使用註解方式定義一個控制器類,並編寫接收和響應JSON格式資料的testJson文法,在方法中列印接受到的JSON使用者資料,然後返回JSON格式的使用者物件。
六、啟動應用,測試專案,輸入地址:http://localhost:8080/ssm/mvc/jsonTest.jsp
輸入張三、北京某個地方,提交,頁面將顯示: