Only find ways to succeed, not excuses for failure!

The following is a demonstration of how to bind parameters through five common annotations:

1. @ pathvariable annotation

@Pathvariable is used to obtain the dynamic parameters in the request URL. The variables in the URL can be mapped to the parameters of the function processing method. The {XXX} placeholder in the URL can be bound to the input parameters of the operation method through @ pathvariable ("XXX").

Example code:
Meta">@ResponseBody    

输出结果:

通过PathVariable获取的参数param1=1通过PathVariable获取的参数param2=2

2.@RequestHeader注解

@RequestHeader 注解,可以把Request请求header部分的值绑定到方法的参数上。

示例代码:
Meta">@ResponseBody    

输出结果:

通过RequestHeader获取的参数param1=abc

3.@CookieValue注解

@CookieValue 可以把Request header中关于cookie的值绑定到方法的参数上。

示例代码:
Meta">@ResponseBody    

输出结果:

通过CookieValue获取的参数sessionid=ebef978eef6c46f8a95cc0990d2d360a

4.@RequestParam注解

@RequestParam注解用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容。提交方式为get或post。(Http协议中,form的enctype属性为编码方式,常用有两种:application/x-www-form-urlencoded和multipart/form-data,默认为application/x-www-form-urlencoded);

@RequestParam注解实质是将Request.getParameter() 中的Key-Value参数Map利用Spring的转化机制ConversionService配置,转化成参数接收对象或字段,get方式中queryString的值,和post方式中body data的值都会被Servlet接受到并转化到Request.getParameter()参数集中,所以@RequestParam可以获取的到;

该注解有三个属性: value、required、defaultValue; value用来指定要传入值的id名称,required用来指示参数是否必录,defaultValue表示参数不传时候的默认值。

示例代码:
Meta">@ResponseBody    

输出结果:

通过RequestParam获取的参数num=10

5.@RequestBody注解

@RequestBody注解用来处理httpentity(请求体)传递过来的数据,一般用来处理非Content-Type: application/x-www-form-urlencoded编码格式的数据;

GET请求中,因为没有httpentity,所以@RequestBody并不适用;

POST请求中,通过httpentity传递的参数,必须要在请求头中声明数据的类型Content-Type,SpringMVC通过使用HandlerAdapter配置的HttpMessageConverters来解析httpentity中的数据,然后绑定到相应的bean上。

示例代码:
Meta">@ResponseBody    

代码运行结果:

通过RequestBody获取的参数bodyStr=这是body的内容


下面的是我的公众号二维码图片,欢迎关注,欢迎留言,一起学习,一起进步。



总结

以上是编程之家为你收集整理的只为成功找方法,不为失败找借口!全部内容,希望文章能够帮你解决只为成功找方法,不为失败找借口!所遇到的程序开发问题。

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。

喜欢与人分享编程技术与工作经验,欢迎加入编程之家官方交流群!

编程之家官方1群

编程之家官方2群



The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>