Spring MVC + jQuery AJAX 向后台传递数据的几种方式

要理解这篇文章,先看Spring MVC 接收请求参数的注解和响应注解

要使用$.ajax({})方法 需要再maven项目下添加jquery依赖

否则会报错  Uncaught ReferenceError: $ is not defined 就是因为项目中没有jQuery依赖

		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>jquery</artifactId>
			<version>3.3.1-2</version>
		</dependency>

 然后再jsp文件添加如下代码 web-demo-test是我的项目名称

<script src="/web-demo-test/webjars/jquery/3.3.1-2/jquery.js"></script>
<script src="/web-demo-test/webjars/jquery/3.3.1-2/jquery.min.js"></script>

1.通过ajax的url路径 传递参数 + 后台用Spring @PathVariable注解 接收参数

  • 1.1 jsp页面 
<script>
	function test() {
		$.ajax({
			async : false,
			cache : false,
			type : 'POST',
			url : '/web-demo-test/student/add/' +"lisi"+ '/' +33,//(1)请求的action路径,可以传递参数到后台
			error : function() {
				alert('请求失败 ');
			},
			success : function(data) {
				alert(data);
			}
		});
	}
</script>
  • 1.2 java 控制器方法 通过Spring 注解 @PathVariable() 接收参数,可以接收基本类型
package com.mx.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/student")
public class StudentController {

	/* 接收url中传来的参数@PathVariable("name") String name,可以接收基本类型 */
	@RequestMapping(value = "/add/{name}/{age}", method = RequestMethod.POST)
	@ResponseBody
	public void addStudent(@PathVariable("name") String name, @PathVariable("age") Long age) {
		System.out.println(name);
		System.out.println(age);

	}
}

2.通过 ajax的data属性 传递参数 + Spring @RequestParam()注解 接收参数(@RequestParam()注解可以省略

  • 2.2 前台 jsp页面
<script>
function submitAjax(){
	
	var postData = { //(2)传递参数到后台,注意后台接收方式 
			"name" : "zhangsan",
			"age" : 24,
			"ids" : "254,249,248"
		}
		/**重点:ajax的type,url,dataType,data属性*/
		$.ajax({
			async : false,
			cache : false,
			type : 'POST',
			url : '/web-demo-test/student/add',
			dataType : "json",
			data : postData,
			error : function() {
				alert('请求失败 ');
			},
			success : function(data) {
				alert(data);
			}

		});
	}
</script>
  • 2.2 java 控制器方法 通过Spring 注解 @RequestParam() 接收参数,可以接收基本类型

这种方式可以接收 各种数据类型,比如String Long 数组 (前台是字符串,后台是数组接收根据逗号把字符串分割成数组 看参数ids)

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/student")
public class StudentController {

 
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public void addStudent(@RequestParam("name") String name, @RequestParam("age") Long age,
			@RequestParam("ids") Long[] ids) {
		System.out.println(name);
		System.out.println(age);
		for (int i = 0; i < ids.length; i++) {
			System.out.println(ids[i]);
		}

	}
}
  • 2.3 如果ajax 是通过ajax data属性传递参数,@RequestParam()注解可以省略保持方法参数名和ajax传过来的data key值一致
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/student")
public class StudentController {

 
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public void addStudent(String name, Integer age, Long[] ids) {
		System.out.println(name);
		System.out.println(age);
		for (int i = 0; i < ids.length; i++) {
			System.out.println(ids[i]);
		}
	}
}

3.通过 ajax的data属性 传递参数 + 编码方式contentType : 'application/json',+ Spring @RequestBody()注解 接收参数

  • Http请求 传递参数的几种编码方式(content-type):默认的application/x-www-form-urlcoded;application/json;application/xml
  • Spring的 @requestBody注解常用来处理 application/json类型,
  • 如果要在在maven项目添加如下依赖,使得项目可以支持application/json编码方式
		<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.9.0</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>2.9.0</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.9.0</version>
		</dependency>
  •  3.1 jsp 代码
<script>
	function test() {
		var postData = { //第一步:定义json数据
			"name" : "echo",
			"age" : 21
		}
		$.ajax({
			async : false,
			cache : false,
			type : 'POST',
			url : '/web-demo-test/student/add',
			contentType : 'application/json', //第二步:定义格式
			dataType : "json",
			data : JSON.stringify(postData),//第三步;把json转为String传递给后台
			error : function() {
				alert('请求失败 ');
			},
			success : function(data) {
				alert(data);
			}

		});
	}
</script>
  • 3.2 如果有Student实体类 包含name,age属性,那么 @requestBody Student student这种形式会将JSON字符串中的值赋予user中对应的属性上
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 com.mx.entity.Student;

@Controller
@RequestMapping("/student")
public class StudentController {
	 
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public String addStudent(@RequestBody Student student) {
		System.out.println(student.toString());
		return "ok";
	}

	 
}
  •  3.2 如果没有实体类可以映射ajax传过来的json数据  @requestBody 以map方式接收json参数
import java.util.Map;

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;

@Controller
@RequestMapping("/student")
public class StudentController1 {

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public String addStudent(@RequestBody Map<String, Object> map) {
		System.out.println("map.get(name)===" + map.get("name"));
		System.out.println("map.get(age)===" + map.get("age"));
		return "ok";
	}

}

 

原文章地址 jQuery AJAX方法 前台往后台传数据 

 

 

posted on 2020-02-26 18:32  dreamstar  阅读(1117)  评论(0编辑  收藏  举报