SpringMVC传递参数

1.springmvc 参数是包装类如何传递

2.@RequestParam

3.@RequestBody

4.@PathVariable

5.jquery如何传递DELETE请求

1.springmvc 参数是包装类如何传递

package com.example.SpringBootDemo1;

import java.util.List;

public class FF {

	private String title;
	
	private String password;
	
	private Integer city;
	
	private List<String>like;
	
	private Boolean sw;
	
	private String sex;
	
	private Person person;

	private List<Animal> animalList;
	
	@Override
	public String toString() {
		return "FF [title=" + title + ", password=" + password + ", city=" + city + ", like=" + like + ", sw=" + sw
				+ ", sex=" + sex + ", person=" + person + ", animalList=" + animalList + "]";
	}

	public List<Animal> getAnimalList() {
		return animalList;
	}

	public void setAnimalList(List<Animal> animalList) {
		this.animalList = animalList;
	}

	public Person getPerson() {
		return person;
	}

	public void setPerson(Person person) {
		this.person = person;
	}

	public List<String> getLike() {
		return like;
	}

	public void setLike(List<String> like) {
		this.like = like;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Integer getCity() {
		return city;
	}

	public void setCity(Integer city) {
		this.city = city;
	}

	public Boolean getSw() {
		return sw;
	}

	public void setSw(Boolean sw) {
		this.sw = sw;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}


}
package com.example.SpringBootDemo1;

public class Person {

	private String grade;
	
	private String clazz;

	@Override
	public String toString() {
		return "Person [grade=" + grade + ", clazz=" + clazz + "]";
	}

	public String getGrade() {
		return grade;
	}

	public void setGrade(String grade) {
		this.grade = grade;
	}

	public String getClazz() {
		return clazz;
	}

	public void setClazz(String clazz) {
		this.clazz = clazz;
	}
	
	
}

 

package com.example.SpringBootDemo1;

public class Animal {

	private Integer age;
	
	private String color;

	@Override
	public String toString() {
		return "Animal [age=" + age + ", color=" + color + "]";
	}

	public Integer getAge() {
		return age;
	}

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

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}
	
	
}

 

	@RequestMapping(value="/ff",method=RequestMethod.POST)
	@ResponseBody
	public FF f(FF f) {
		System.out.println(f);
		return f;
	}

 

<script>
$(function(){
	
	$("#b").click(function(){
		var data={"title":"主题","password":"123",
				"like[0]":"girl","like[1]":"swim",
				"sw":1,
				"person.grade":"一年级","person.clazz":"200班",
				"animalList[0].age":"10","animalList[0].color":"red",
				"animalList[1].age":"26","animalList[1].color":"blue"};
		
		
		 $.post("ff",data,function(){
			 
		 });
	});
	
	
});

如果是在json数据上修改属性,比如data.field是现成的json。

data.field["xxx"]=""这样可行,data.field.xxx=""没有效果.

规则是:如果包装类一个属性是对象,传参为 "包装类属性名.对象属性名"="值";

如果包装类属性是list<String>,传参为 "包装类属性名[索引]"=“值”;

如果包装类属性 是list<类>,传参为  "包装类属性名[索引].类属性"="值"

form.on('submit(formDemo)', function(data){
    layer.msg(JSON.stringify(data.field));
    
     var nameLike = $("input[name='like']:checked");
  	nameLike.each(function(index,element){
  		data.field["like["+index+"]"]=element.value;
  	});
  	
  	data.field["person.grade"]="一年级";
  	data.field["person.clazz"]="200班";
	data.field["animalList[0].age"]="20";
	data.field["animalList[1].age"]="30";
	data.field["animalList[0].color"]="green";
	data.field["animalList[1].color"]="blue";
  	
 	/*错的 data.field.like[0]="a";
  	data.field.like[1]="b"; */
  //	data.field["like[0]"]="a";
  	//data.field["like[1]"]="b";
  	
    $.post("/ff", data.field, function(str){
  	  layer.open({
  	    content: str ,//注意,如果str是object,那么需要字符拼接。
  	    skin:'layui-layer-molv'
  	  });
  	});

json格式本来是{"name":"melo","age":"18","person":{"grade":"一年级","clazz":"200班"},"animal":[{"color":"red"},{"color:blue"}]}.

但这样传springmvc,基本属性可以穿进去,包装对象和list传不进去,要想后台直接接受为对象只能上述写法。

或者可以JSON.stringify() 把标准格式的json放进去,做参数传后台,这时候后台参数就是json,参数类型是String,还需要写一行代码,把参数 转换成对象类型。

2.@RequestParam

这个注解就相当于request.getParameter("name") 从请求中拿参数。

注解属性有value,value是什么,前端传递的key就是什;required=true代表这个参数必须传;defaultValue:默认值,如果设置了该值,required 将自动设为 false,无论你是否配置了required,配置了什么值,都是 false(可选配置)

只能注解在基本数据类型前,前端按照json格式传递ok。如果注解在包包装类对象前,无法传递进去。所以包装类参数及不要加注解了,就用上述第一点那样格式传递即可

 

平常不加这个注解,参数也能传递,那要它干什么?这个注解如果不给value值,spring认为这个参数必须传递,如果不传递就会报错,如果不加这个注解,参数即使不传递也不会报错,只是显示null。这个注解可以给基本类型的参数做限制。

 

传基本类型:ok

	@PostMapping("aa")
	@ResponseBody
	public void aa(@RequestParam("aa")String aa,@RequestParam("cc")Integer bb) {
		System.out.println(aa+bb);
	}

 $("#b1").click(function(){
		 $.post("aa",{"aa":"melo","cc":"18"},function(){
			 
		 });
	 });

传包装类型:失败,{"timestamp":1552784677033,"status":400,"error":"Bad Request","exception":"org.springframework.web.bind.MissingServletRequestParameterException","message":"Required Person parameter 'person' is not present","path":"/bb"}

 $("#b2").click(function(){
		 $.post("bb",{"grade":"1","clazz":"200"},function(){
			 
		 });
	 });


@PostMapping("bb")
	@ResponseBody
	public void bb(@RequestParam("person")Person person) {
		System.out.println(person);
	}

 

不管get请求还是post请求,在jq ajax中,参数都是写在data中。只是在浏览器请求显示中,get请求的参数会显示在url路径上。

	@GetMapping("aa")
	@ResponseBody
	public void a(@RequestParam("aa")String aa,@RequestParam("cc")Integer bb) {
		System.out.println(aa+bb);
	}

	@PostMapping("aa")
	@ResponseBody
	public void aa(@RequestParam("aa")String aa,@RequestParam("cc")Integer bb) {
		System.out.println(aa+bb);
	}

	 $("#b3").click(function(){
		 $.get("aa",{"aa":"melo","cc":"18"},function(){
			 
		 });
	 });

	 $("#b1").click(function(){
		 $.post("aa",{"aa":"melo","cc":"18"},function(){
			 
		 });
	 });

3.@PathVariable

@PathVariable是很有意思的注解。容易和@RequetParam混淆。

@RequetParam获取的是请求中的参数,在jq ajax中参数是写在data部分的;@PathVariable获取的是url路径上的参数变量,在jqajax参数写在url上。

在get的请求下,请求中的会显示在浏览器的url上,但@PathVariable是/xxx/yyy 显示的。而@RequetParam是xxx?yyy=zzz现实的

看一下@PathVariable如何使用。url 参数变量用{xxx}括起,@PathVariable(value="xxx")获取url参数赋值给方法参数。

前端传递在请求参数中设置值是没有用的,必须把传递的参数写在url上;如果是@RequestParm,依然把参数写在data部分。

@GetMapping("cc/{name}/{age}")
	@ResponseBody
	public void cc(@PathVariable("name")String name,@PathVariable("age")Integer age) {
		System.out.println("姓名="+name + ",年龄"+age);
	}

 $("#b4").click(function(){
		$.get("cc/james/18",{"name":"melo","age":"18"},function(){
			 
		 });
		 
	 });

@PathVariable在其他请求类型中也可以使用,试试delete,ok

            $.ajax({
			     url: 'cc/melo/26',
			     type: 'POST',
			     data:{"_method":"DELETE"},
			     success: function(result) {
			     }
			 });


     @DeleteMapping("cc/{name}/{age}")
	@ResponseBody
	public void c(@PathVariable("name")String name,@PathVariable("age")Integer age) {
		System.out.println("姓名="+name + ",年龄"+age);
	}

 

使用场景:

  1. 当URL指向的是某一具体业务资源(或者资源列表),例如博客,用户时,使用@PathVariable
  2. 当URL需要对资源或者资源列表进行过滤,筛选时,用@RequestParam

例如我们会这样设计URL:

  1. /blogs/{blogId}
  2. /blogs?state=publish而不是/blogs/state/publish来表示处于发布状态的博客文章

同一个url但不同的用户不同的参数展示不同的内容,就适合@PathVariable。csdn文章详情和按时间查询的文章列表都是这样

.

4.@RequestBody

以前一直以为在SpringMVC环境中,@RequestBody接收的是一个Json对象,一直在调试代码都没有成功,后来发现,其实 @RequestBody接收的是一个Json对象的字符串,而不是一个Json对象。然而在ajax请求往往传的都是Json对象,后来发现用 JSON.stringify(data)的方式就能将对象变成字符串。同时ajax请求的时候也要指定dataType: "json",contentType:"application/json" 这样就可以轻易的将一个对象或者List传到Java端,使用@RequestBody即可绑定对象或者List.

转载https://www.cnblogs.com/chenkeyu/p/8482440.html

@RequestParam

用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容。(Http协议中,如果不指定Content-Type,则默认传递的参数就是application/x-www-form-urlencoded类型)

RequestParam可以接受简单类型的属性,也可以接受对象类型。 
实质是将Request.getParameter() 中的Key-Value参数Map利用Spring的转化机制ConversionService配置,转化成参数接收对象或字段。

tip

Content-Type: application/x-www-form-urlencoded的请求中, 
get 方式中queryString的值,和post方式中 body data的值都会被Servlet接受到并转化到Request.getParameter()参数集中,所以@RequestParam可以获取的到。

@RequestBody

处理HttpEntity传递过来的数据,一般用来处理非Content-Type: application/x-www-form-urlencoded编码格式的数据。

  • GET请求中,因为没有HttpEntity,所以@RequestBody并不适用。
  • POST请求中,通过HttpEntity传递的参数,必须要在请求头中声明数据的类型Content-Type,SpringMVC通过使用HandlerAdapter 配置的HttpMessageConverters来解析HttpEntity中的数据,然后绑定到相应的bean上。

总结

  • 在GET请求中,不能使用@RequestBody。
  • 在POST请求,可以使用@RequestBody和@RequestParam,但是如果使用@RequestBody,对于参数转化的配置必须统一。

举个例子,在SpringMVC配置了HttpMessageConverters处理栈中,指定json转化的格式,如Date转成‘yyyy-MM-dd’,则参数接收对象包含的字段如果是Date类型,就只能让客户端传递年月日的格式,不能传时分秒。因为不同的接口,它的参数可能对时间参数有不同的格式要求,所以这样做会让客户端调用同事对参数的格式有点困惑,所以说扩展性不高。

如果使用@RequestParam来接受参数,可以在接受参数的model中设置@DateFormat指定所需要接受时间参数的格式。

另外,使用@RequestBody接受的参数是不会被Servlet转化统一放在request对象的Param参数集中,@RequestParam是可以的。

综上所述,一般情况下,推荐使用@RequestParam注解来接受Http请求参数。

 

5.jquery如何传递DELETE请求,没有接受到参数

type依然写成post,在data中加_method 值是DELETE

             $.ajax({
			     url: 'cc/melo/26',
			     type: 'POST',
			     data:{"_method":"DELETE"},
			     success: function(result) {
			     }
			 });

PUT请求不需要,可以接受到参数,传对象也可以

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值