前言
接受参数是我们在日常开发中经常会遇到的一个需求,下面这篇文章主要给大家介绍了关于spring boot接收单个string入参之解决方案的相关内容,下面话不多说了,来一起看看详细的介绍吧
场景:
在做接口时,有的时候,接口入参只需要一个参数,如果将一个参数封装成一个对象很麻烦,故有了以下方式:
思路:
spring自带的参数解析器貌似是不具备这个能力的,所有自定义
方式方法:
1.定义一个注解
1
2
3
4
5
6
7
8
9
10
|
@target (elementtype.parameter) @retention (retentionpolicy.runtime) @documented public @interface requestsingleparam { string value(); boolean required() default true ; string defaultvalue() default "" ; } |
2.定义解析器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
public class requestsingleparamhandlermethodargumentresolver implements handlermethodargumentresolver { @override public boolean supportsparameter(methodparameter parameter) { return parameter.hasparameterannotation(requestsingleparam. class ); } @override public object resolveargument(methodparameter parameter, modelandviewcontainer mavcontainer, nativewebrequest webrequest, webdatabinderfactory binderfactory) throws exception { requestsingleparam requestsingleparam = parameter.getparameterannotation(requestsingleparam. class ); httpservletrequest request = webrequest.getnativerequest(httpservletrequest. class ); bufferedreader reader = request.getreader(); stringbuilder sb = new stringbuilder(); char [] buf = new char [ 1024 ]; int rd; while ((rd = reader.read(buf)) != - 1 ) { sb.append(buf, 0 , rd); } jsonobject jsonobject = jsonobject.parseobject(sb.tostring()); string value = requestsingleparam.value(); return jsonobject.get(value); } } |
3.修改springboot启动类
(a.继承webmvcconfigureradapter;b.重写addargumentresolvers()方法)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@springbootapplication @enablewebmvc public class springbootdemoapplication extends webmvcconfigureradapter { public static void main(string[] args) { springapplication.run(springbootdemoapplication. class , args); } @override public void addargumentresolvers(list<handlermethodargumentresolver> argumentresolvers){ argumentresolvers.add( new requestsingleparamhandlermethodargumentresolver()); super .addargumentresolvers(argumentresolvers); } } |
4.在controller中应用
调用接口方,传参如: {“name”:"张三"},controller中就能获取到"张三”
1
2
3
4
|
@requestmapping (value = "/test" ,method = requestmethod.post) public void test( @requestsingleparam (value = "name" ) string name){ system.out.println(name); } |
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。
原文链接:http://www.cnblogs.com/swugogo/p/9885509.html