国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

玩轉spring boot 結合jQuery和AngularJs(3)

2019-11-26 13:19:49
字體:
來源:轉載
供稿:網友

上篇的基礎上

準備工作:

修改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 http://maven.apache.org/xsd/maven-4.0.0.xsd">  <modelVersion>4.0.0</modelVersion>  <groupId>com.github.carter659</groupId>  <artifactId>spring03</artifactId>  <version>0.0.1-SNAPSHOT</version>  <packaging>jar</packaging>  <name>spring03</name>  <url>http://maven.apache.org</url>  <parent>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-parent</artifactId>    <version>1.4.2.RELEASE</version>  </parent>  <properties>    <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>    <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-devtools</artifactId>      <optional>true</optional>    </dependency>  </dependencies>  <build>    <plugins>      <plugin>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-maven-plugin</artifactId>      </plugin>    </plugins>  </build></project>

修改App.java

package com.github.carter659.spring03;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class App {    public static void main(String[] args) {    SpringApplication.run(App.class, args);  }  }

新建“Order.java”類文件:

package com.github.carter659.spring03;import java.util.Date;public class Order {  public String no;  public Date date;  public int quantity;}

說明一下:這里我直接使用public字段了,get/set方法就不寫了。

新建控制器“MainController”:

package com.github.carter659.spring03;import java.time.ZoneId;import java.util.HashMap;import java.util.Map;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.ResponseBody;@Controllerpublic class MainController {  @GetMapping("/")  public String index() {    return "index";  }  @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 quantity, String date) {    System.out.println("no:" + no);    System.out.println("quantity:" + quantity);    System.out.println("date:" + date);    Map<String, Object> map = new HashMap<>();    map.put("msg", "ok");    map.put("quantity", quantity);    map.put("no", no);    map.put("date", date);    return map;  }  @PostMapping("/postJson")  public @ResponseBody Map<String, Object> postJson(@RequestBody Order order) {    System.out.println("order no:" + order.no);    System.out.println("order quantity:" + order.quantity);    System.out.println("order date:" + order.date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());    Map<String, Object> map = new HashMap<>();    map.put("msg", "ok");    map.put("value", order);    return map;  }}

新建jquery.html文件:

<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>jquery</title><script src="http://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script><script type="text/javascript">  /*<![CDATA[*/  function postData() {    var data = 'no=' + $('#no').val() + '&quantity=' + $('#quantity').val()        + '&date=' + $('#date').val();    $.ajax({      type : 'POST',      url : '/postData',      data : data,      success : function(r) {        console.log(r);      },      error : function() {        alert('error!')      }    });  }  function postJson() {    var data = {      no : $('#no').val(),      quantity : $('#quantity').val(),      date : $('#date').val()    };    $.ajax({      type : 'POST',      contentType : 'application/json',      url : '/postJson',      data : JSON.stringify(data),      success : function(r) {        console.log(r);      },      error : function() {        alert('error!')      }    });  }  /*]]>*/</script></head><body>  no:  <input id="no" value="No.1234567890" />  <br /> quantity:  <input id="quantity" value="100" />  <br /> date:  <input id="date" value="2016-12-20" />  <br />  <input value="postData" type="button" onclick="postData()" />  <br />  <input value="postJson" type="button" onclick="postJson()" /></body></html>

新建“angularjs.html”文件:

<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>angularjs</title><script src="http://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;      });    }  });</script></head><body ng-app="app" ng-controller="MainController">  no:  <input id="no" ng-model="data.no" />  <br /> quantity:  <input id="quantity" ng-model="data.quantity" />  <br /> date:  <input id="date" ng-model="data.date" />  <br />  <input value="postJson" type="button" ng-click="postJson()" />  <br />  <br />  <div>{{responseBody}}</div></body></html>

項目結構如下圖:

一、結合jquery

運行App.java后進去“http://localhost:8080/jquery”頁面

點擊“postData”按鈕:

jquery成功的調用了spring mvc的后臺方法“public @ResponseBody Map<String, Object> postData(String no, int quantity, String date)”

這里,“date”參數我使用的是String類型,而并不是Date類型。因為大多數情況是使用對象形式來接收ajax客戶端的值,所以我這里偷懶了,就直接使用String類型。如果想使用Date類型,則需要使用@InitBinder注解,后面的篇幅中會講到,在這里就不再贅述。

另外,使用“thymeleaf”模板引擎在編寫js時,“&”關鍵字要特別注意,因為“thymeleaf”模板引擎使用的是xml語法。因此,在<script>標簽的開始――結束的位置要加“/*<![CDATA[*/ ...../*]]>*/”

例如:

<script type="text/javascript">  /*<![CDATA[*/    // javascript code ...  /*]]>*/</script>

否則,運行“thymeleaf”模板引擎時就會出現錯誤“org.xml.sax.SAXParseException:...”

點擊“postJson”按鈕:

jquery則成功調用了后臺“public @ResponseBody Map<String, Object> postJson(@RequestBody Order order)”方法,

并且參數“order”中的屬性或字段也能被自動賦值,而Date類一樣會被賦值。

注意的是:在使用jquery的$.ajax方法時,contentType參數需要使用“application/json”,而后臺spring mvc的“postJson”方法中的“order”參數也需要使用@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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 潞城市| 宝丰县| 东光县| 桓仁| 斗六市| 策勒县| 江安县| 滨州市| 博乐市| 莱阳市| 邓州市| 治县。| 汉川市| 秭归县| 依安县| 达拉特旗| 萝北县| 罗平县| 砀山县| 新和县| 清水河县| 广州市| 汉源县| 长寿区| 昭苏县| 三原县| 朝阳区| 怀安县| 灵寿县| 贵阳市| 射洪县| 鄄城县| 宝清县| 乳源| 日喀则市| 绵竹市| 濮阳县| 攀枝花市| 阳江市| 泰和县| 绍兴县|