在上篇的基础上
准备工作 :
修改 pom.xml
<Project xmlns = "http://maven.apache.org/pom/4.0.0" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xsi: schemalocation = "http://maven.apache.org/pom/4.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0. http://maven.apache.org/xsd/maven-4.0.0.xsd "> <modelVersion> 4.0.0 </modelversion> <MoupRupid> com.github.carter659 </groupid> <artifactid> spring03 </artifactID> <PROPESSON <name> spring03 </name> <sl> http://maven.apache.org </ url> <-parent> <grupid> org.springframework.boot </groupid> <artifactid> spring-boot-starter-parent </artifactid> <version> 1.4.20ease </versevers> </parent> <propiedades> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <Spendency> <MoupRoMID> org.springframework.boot </groupid> <artifactid> spring-boot-devlools </arfactid> <pectional> true </pectional> </dependency> </dependencias> <construcción> <glugins> <glugin> <proupid> org.springframework.boot </proupid> <artifactID> spring-boot-saven-plugin </artifactid> </glugin> </glugins> </build> </proyecto>
修改 App.java
paquete com.github.carter659.spring03; import org.springframework.boot.springapplication; import org.springframework.boot.autoconfigure.springbootapplication; @SpringBootapplationPplicationPpublic Class App {PublicStatic Static Main (String [] Args) {SpringApplication.Run (App.ClassClaSsClass, Args, args (args); }}新建 “Order.java” 类文件 :
paquete com.github.carter659.spring03; import java.util.date; orden de clase pública {public String no; Fecha de fecha pública; Public int Cantidad;}说明一下 : 这里我直接使用 público 字段了 字段了 字段了 方法就不写了。 方法就不写了。
新建控制器 "MainController":
paquete com.github.carter659.spring03; import java.time.zoneid; import java.util.hashmap; import java.util.map; import org.springframework.stereotype.controller; import og.springfframework.web.bind.annotation.getMapping; import org.springframework.web.bind.annotation.postmapping; import org.springframework.web.bind.annotation.requestbody; import org.springframework.web.bind.annotation.resesponseBody; @ControllerPublic Classer Controller {@getmapping ("/") Index (Índice de retorno "; } @Getmapping ("/jQuery") public string jQuery () {return "jQuery"; } @Getmapping ("/angularjs") public string angularjs () {return "angularjs"; } @Postmapping ("/postdata") public @ResponseBody Map <String, Object> PostData (String No, int Cantidad, String Date) {System.out.println ("No:" + No); System.out.println ("Cantidad:" + cantidad); System.out.println ("fecha:" + fecha); Map <string, object> map = new HashMap <> (); map.put ("msg", "ok"); map.put ("cantidad", cantidad); map.put ("no", no); map.put ("fecha", fecha); mapa de retorno; } @PostMapping ("/postjson") public @ResponseBody Map <String, Object> Postjson (@RequestBody Order Order) {System.out.println ("Orden no:" + orden.no); System.out.println ("Cantidad de pedido:" + orden.quantity); System.out.println ("Fecha de pedido:" + orden.date.toinstant (). Atzone (ZoneId.SystemDefault ()). TOLOCALDATE ()); Map <string, object> map = new HashMap <> (); map.put ("msg", "ok"); map.put ("valor", orden); mapa de retorno; }}新建 jQuery.html 文件:
<! Doctype html> <html xmlns: th = "http://www.thymeleaf.org"> <fead> <meta http-equiv = "content-type" content = "text/html; charset = utf-8"/> <title> jQuery src = "// cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script><script type =" text/javascript ">/*<! [cdata [*/function postdata () {var data = 'no =' + $ (no '). Val () +' 'y cantidad =' + $ (('#cuantity'). '& date =' + $ ('#date'). val (); $ .AJAX ({type: 'post', url: '/postdata', data: data, éxito: function (r) {console.log (r);}, error: function () {alert ('error!')}}); } function postjson () {var data = {no: $ ('#no'). val (), cantidad: $ ('#cantidad'). val (), fecha: $ ('#date'). val ()}; $ .AJAX ({Tipo: 'Post', ContentType: 'Application/Json', URL: '/Postjson', Data: Json.Stringify (Data), Success: Function (R) {Console.log (r);}, error: function () {alerta ('Error!')}}); } /*]]]>* /< /script> </head> <body> no: <input id = "no" valor = "No.1234567890" /> <br /> cantidad: <input id = "cantidad" valor = "100" /> <Br /> date: <input id = "fecha" value = "2016-12-20" /> <br /> <input value = "Postdata" Botón "Botón" onClick = "postdata ()" /> <br /> <input value = "postjson" type = "button" onClick = "postjson ()" /> </body> < /html>新建 “Angularjs.html” 文件 :
< src = "// cdn.bootcss.com/angular.js/1.5.6/angular.min.js"></script><script type =" text/javaScript "> var app = angular.module ('app', []); app.controller('MainController', function($rootScope, $scope, $http) { $scope.data = { no : 'No.1234567890', quantity : 100, 'date' : '2016-12-20' }; $scope.postJson = function() { $http({ url : '/postJson', method : 'POST', data : $ scope.data}). Success (function (r) {$ scope.responseBody = r;}); ng-model = "data.quantity" /> <br /> date: <input id = "date" ng-model = "data.date" /> <br /> <input value = "postjson" type = "button" ng-click = "postjson ()" /> <br /> <Br /> <Viv> {ResponseBody}} </iv> </body> < /html>项目结构如下图 :
一、结合 jQuery
运行 App.java 后进去 “http: // localhost: 8080/jQuery” 页面
点击 “PostData” 按钮 :
jQuery 成功的调用了 Spring MVC 的后台方法 "public @ResponseBody Map <String, Object> PostData (String No, int Cantidad, Fecha de cadena)"
这里 , "Fecha" 参数我使用的是 String 类型 , 而并不是 Fecha 类型。因为大多数情况是使用对象形式来接收 Ajax 客户端的值 , 所以我这里偷懒了 , 就直接使用 String 类型。如果想使用 Fecha 类型 则需要使用 则需要使用 @Initbinder 注解 , 后面的篇幅中会讲到 在这里就不再赘述。 在这里就不再赘述。
另外 , 使用 使用 “thymeleaf” 模板引擎在编写 js 时 , “&” 关键字要特别注意 , 因为 “thymeleaf” 模板引擎使用的是 xml 语法。因此 , 在 <script> 标签的开始 —– 结束的位置要加 “/*<! [Cdata [*/...../*]]>*/”
例如 :
<script type = "text/javaScript">/*<! [cdata [*/// código javascript .../*]]>*/</script>
否则 , 运行 运行 "thymeleaf" 模板引擎时就会出现错误 “org.xml.Sax.SaxParseException: ..."
点击 "Postjson" 按钮 :
jQuery 则成功调用了后台 "public @ResponseBody Map <String, Object> Postjson (@RequestBody Order Order)" 方法 方法
并且参数 “orden” 中的属性或字段也能被自动赋值 而 而 Fecha 类一样会被赋值。
注意的是 : 在使用 jQuery 的 $ .AJAX 方法时 , ContentType 参数需要使用 “Aplicación/JSON” , 而后台 Spring MVC 的 “Postjson” 方法中的 “Orden” 参数也需要使用 @RequestBody 注解。
二、结合 Angularjs
进入 “后进去 后进去 http: // localhost: 8080/angularjs” 页面
点击 "Postjson" 按钮 :
使用 Angularjs 后 依然能调用 依然能调用 “public @ResponseBody Map <String, Object> Postjson (@RequestBody Order Order)” 方法。
代码 : https: //github.com/carter659/spring-boot-03.git
以上就是本文的全部内容 , 希望对大家的学习有所帮助 也希望大家多多支持武林网。 也希望大家多多支持武林网。