溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何在AngularJs中結(jié)合SpringMVC使用

發(fā)布時(shí)間:2020-11-25 15:29:40 來源:億速云 閱讀:138 作者:Leah 欄目:編程語言

本篇文章給大家分享的是有關(guān)如何在AngularJs中結(jié)合SpringMVC使用,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

首先我們把springmvc的環(huán)境搭好,先來web.xml

<&#63;xml version="1.0" encoding="UTF-8"&#63;>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 <display-name>SpringMVC</display-name>
 <context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>/WEB-INF/AngularJSTestApplicationContext.xml</param-value>
 </context-param>

 <listener>
 <listener-class>
  org.springframework.web.context.ContextLoaderListener
 </listener-class>
 </listener>

 <servlet>
 <servlet-name>baobaotao</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <init-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/AngularJSTestApplicationContext.xml</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
 <servlet-name>baobaotao</servlet-name>
 <url-pattern>*.do</url-pattern>
 </servlet-mapping>
</web-app>

這里我把a(bǔ)pplicationContext改了一個(gè)名字,以免和我自己本身用的沖突,并且設(shè)置了一下觸發(fā)springmvc的url模式,是以.do結(jié)尾發(fā)起請(qǐng)求

下面是AngularJSTestApplicationContext.xml

<&#63;xml version="1.0" encoding="UTF-8"&#63;>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
      http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<mvc:annotation-driven />

<context:component-scan base-package="com.baobaotao.web"/>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/jsp/" />
  <property name="suffix" value=".jsp" />
</bean>
</beans>

我直接用了<mvc:annotation-driven /> 就用默認(rèn)的數(shù)據(jù)轉(zhuǎn)換器了,因?yàn)槟J(rèn)的里面有對(duì)Json串進(jìn)行數(shù)據(jù)綁定的轉(zhuǎn)換器

這樣mvc的環(huán)境已經(jīng)搭建好了,下面我們寫頁面

<%@ 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 ng-app="">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="../angular.js"></script>
<title>AngularJSTest</title>
</head>
<body ng-controller="MyController">
 <p>User</p>
 <p>ID</p>
 <input id="id" name="id" ng-model="saveUser.id">
 <br>
 <p>Name</p>
 <input id="id" name="name" ng-model="saveUser.name">
 <br>
 <p>age</p>
 <input id="id" name="age" ng-model="saveUser.age">
 <br>
 <button ng-click="getUser()">提交</button>
 <script>
  function MyController($scope, $http){
   $scope.saveUser = {
    id:1,
    name:"John",
    age:"16"
   };

   $scope.getUser = function(){
    $http({
     method: "POST",
     url: "http://localhost:8080/SpringMVC/AngularJS/getUser.do",
     data: $scope.saveUser
    }).success(function (data, status){
     // handle success
    })
   };
  }
 </script>
</body>
</html>

頁面很簡單,有三個(gè)輸入?yún)?shù),id,name,age綁定了控制器里面的saveUser對(duì)象的屬性,這個(gè)也對(duì)應(yīng)了我后臺(tái)需要綁定的數(shù)據(jù)的屬性名稱。對(duì)于AngularJs,在body標(biāo)簽處聲明了一個(gè)控制器MyController,之后在script中對(duì)這個(gè)控制器里面的saveUser 對(duì)象屬性進(jìn)行了初始化并且定義了一個(gè)方法getUser,它是傳遞參數(shù)的關(guān)鍵。之后制定了當(dāng)點(diǎn)擊提交按鈕以后會(huì)把數(shù)據(jù)傳遞出去。

看一下getUser方法,看上去很像ajax的提交數(shù)據(jù)方式,指定了請(qǐng)求的方法是Post,請(qǐng)求的地址url以及請(qǐng)求中要發(fā)送的數(shù)據(jù)data,這里我將MyController控制器中的對(duì)象屬性作為數(shù)據(jù)進(jìn)行傳遞,這個(gè)對(duì)象在傳輸?shù)臅r(shí)候會(huì)自動(dòng)的將其結(jié)構(gòu)轉(zhuǎn)換成Json格式進(jìn)行傳遞

下面貼上后臺(tái)Controller的代碼

package com.baobaotao.web;

import com.baobaoto.domain.AngularUser;

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
@RequestMapping(value="/AngularJS")
public class TestAngularJS {

 @RequestMapping("/intro.do")
 public ModelAndView intro(){
  ModelAndView mav = new ModelAndView();
  mav.setViewName("AngularJsTest");
  return mav;
 }
 @RequestMapping(value="/getUser.do", method=RequestMethod.POST)
 public String getUser(@RequestBody AngularUser angularUser){
  System.out.println("ID" + angularUser.getId());
  System.out.println("name" + angularUser.getName());
  System.out.println("age" + angularUser.getAge());
  return null;
 }
}

頁面上的請(qǐng)求映射到了這里的getUser方法,因?yàn)轫撁嫔咸岢龅恼?qǐng)求方法是post,所以我們這里也設(shè)定RequestMapping的method為post,最為關(guān)鍵的就是@RequestBody這個(gè)注釋,其可以將傳來的Json格式的數(shù)據(jù)與Bean中的屬性值進(jìn)行直接綁定,也就是說這里的AngularUser 對(duì)象內(nèi)的屬性已經(jīng)成功的被賦值了,這里貼上AngularUser Bean定義

package com.baobaoto.domain;

public class AngularUser {

 Long id;

 String name;

 String age;

 public Long getId() {
  return id;
 }

 public void setId(Long id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getAge() {
  return age;
 }

 public void setAge(String age) {
  this.age = age;
 }

}

部署到服務(wù)器上運(yùn)行,直接點(diǎn)擊提交按鈕以后后臺(tái)控制臺(tái)結(jié)果

ID1
nameJohn
age16

之后我們將input中的數(shù)值改變?yōu)?、David、17,點(diǎn)擊提交按鈕控制臺(tái)結(jié)果

ID2
nameDavid
age17

測(cè)試成功

從后臺(tái)獲取數(shù)據(jù)

這個(gè)要容易些,對(duì)原有的內(nèi)容適當(dāng)修改就可以了

頁面

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html ng-app="">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="../angular.js"></script>
<title>AngularJSTest</title>
</head>
<body ng-controller="MyController">
 <p>User</p>
 <p>ID</p>
 <input id="id" name="id" ng-model="saveUser.id">
 <br>
 <p>Name</p>
 <input id="id" name="name" ng-model="saveUser.name">
 <br>
 <p>age</p>
 <input id="id" name="age" ng-model="saveUser.age">
 <br>
 <ul>
  <li ng-repeat="x in infos">
   {{ x.ID + x.name + x.age }}
 </li>
 </ul>
 <button ng-click="getUser()">提交</button>
 <script>
  function MyController($scope, $http){
   $scope.saveUser = {
    id:1,
    name:"John",
    age:"16"

   };

   $scope.getUser = function(){
    $http({
     method: "POST",
     url: "http://localhost:8080/SpringMVC/AngularJS/getUser.do",
     data: $scope.saveUser
    }).success(function (data){
     $scope.infos = data;
    })
   };

  }
 </script>
</body>
</html>

這里增加了一個(gè)ul標(biāo)簽用來接收從后臺(tái)傳過來的數(shù)據(jù),里面存儲(chǔ)的是一個(gè)Json數(shù)組,這個(gè)數(shù)組在當(dāng)我們點(diǎn)擊按鈕之后觸發(fā)的回調(diào)函數(shù)中進(jìn)行賦值,而回調(diào)的這個(gè)函數(shù)的參數(shù)data就是我們從后臺(tái)獲取到的數(shù)據(jù),具體data是怎樣的要看后臺(tái)Controller中返回的數(shù)值是怎樣的。這里我們返回的是一個(gè)Json數(shù)組

package com.baobaotao.web;

import com.baobaoto.domain.AngularUser;

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;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value="/AngularJS")
public class TestAngularJS {

 @RequestMapping("/intro.do")
 public ModelAndView intro(){
  ModelAndView mav = new ModelAndView();
  mav.setViewName("AngularJsTest");
  return mav;
 }
 @RequestMapping(value="/getUser.do", method=RequestMethod.POST)
 @ResponseBody
 public List<Map<String, String>> getUser(@RequestBody AngularUser angularUser){
  System.out.println("ID" + angularUser.getId());
  System.out.println("name" + angularUser.getName());
  System.out.println("age" + angularUser.getAge());
  List<Map<String, String>> list = new ArrayList<Map<String, String>>();
  for(int i = 0; i < 5; i++){
   Map<String, String> map = new HashMap<String, String>();
   map.put("ID", String.valueOf(i));
   map.put("name", String.valueOf(i));
   map.put("age", String.valueOf(i));
   list.add(map);
  }
  return list;
 }

}

上面是修改過的Controller,我將返回值改為了一個(gè)list,里面的數(shù)據(jù)是Map這樣就剛好符合Json數(shù)組的數(shù)據(jù)模式了,當(dāng)然最重要的是這里在方法前需要添加一個(gè)@ResponseBody 注釋,它可以把返回的值轉(zhuǎn)化為Json格式的數(shù)據(jù)

好了,運(yùn)行一下程序試試,點(diǎn)擊提交按鈕,出現(xiàn)了結(jié)果

如何在AngularJs中結(jié)合SpringMVC使用

測(cè)試成功

上面這兩種是最簡單的方式實(shí)現(xiàn)了AngularJs和springmvc的結(jié)合使用,基本的功能算是實(shí)現(xiàn)了

以上就是如何在AngularJs中結(jié)合SpringMVC使用,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI