In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article focuses on "SpringBoot how to customize the parameter parser", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "SpringBoot how to customize the parameter parser"!
SpringMVC provides support for parsing http parameters in various postures. As you can see from the previous GET/POST parameter resolution section, you can bind method parameters to http parameters by adding a @ RequsetParam annotation. When you see this, you will naturally wonder how this is done. Can we define a parameter resolution rule by ourselves?
This article will show you how to implement custom parameter resolution and make it effective
i. Environment building
First of all, you have to build a web application before it is possible to continue the follow-up testing. Building a web application with SpringBoot is a relatively simple task.
Create a maven project with the following pom file
Org.springframework.boot spring-boot-starter-parent 2.1.7 UTF-8 UTF-8 Finchley.RELEASE 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-maven-plugin spring-milestones Spring Milestones https://repo.spring.io/milestone false II. Custom parameter parser
For how to customize the parameter parser, a recommended method is to first figure out the complete processing link after springmvc receives a request, and then to see where and when to insert the custom parameter parser, which is much easier to understand and implement. Unfortunately, the main goal of this article is to use, so here we will simply mention the link of parameter parsing, leaving the details to the subsequent source code parsing.
1. Parameter resolution link
Http request flowchart, from SpringBoot how to parse HTTP parameters
Since it is parameter parsing, it must be triggered before the method call. In Spring, it is responsible for associating the http parameters with the target method parameters, mainly with the help of the org.springframework.web.method.support.HandlerMethodArgumentResolver class.
/ * * Iterate over registered {@ link HandlerMethodArgumentResolver} s and invoke the one that supports it. * @ throws IllegalStateException if no suitable {@ link HandlerMethodArgumentResolver} is found. * / @ Override@Nullablepublic Object resolveArgument (MethodParameter parameter, @ Nullable ModelAndViewContainer mavContainer, NativeWebRequest webRequest, @ Nullable WebDataBinderFactory binderFactory) throws Exception {HandlerMethodArgumentResolver resolver = getArgumentResolver (parameter); if (resolver = = null) {throw new IllegalArgumentException ("Unknown parameter type [" + parameter.getParameterType (). GetName () + "]");} return resolver.resolveArgument (parameter, mavContainer, webRequest, binderFactory);}
The core code above comes from org.springframework.web.method.support.HandlerMethodArgumentResolverComposite#resolveArgument. The main function is to obtain a suitable HandlerMethodArgumentResolver and map the http parameter (webRequest) to the parameter of the target method (parameter).
So, the core of implementing a custom parameter parser is to implement your own HandlerMethodArgumentResolver
2. HandlerMethodArgumentResolver
To implement a custom parameter parser, we must first have a goal. In the get parameter parsing section, we encountered a problem at that time: when passing parameters to an array, the defined method parameters need to be an array, not List, otherwise they cannot be parsed properly. Now we hope to implement such a parameter parsing to support the above scenario.
To achieve this small goal above, we can do the following
a. Custom Annotation ListParam
The main purpose of defining this annotation is to indicate that the parameter with this annotation can be parsed using our custom parameter parser.
@ Target (ElementType.PARAMETER) @ Retention (RetentionPolicy.RUNTIME) @ Documentedpublic @ interface ListParam {/ * * Alias for {@ link # name} * / @ AliasFor ("name") String value () default "; / * The name of the request parameter to bind to. * * @ since 4.2 * / @ AliasFor ("value") String name () default "";} b. Parameter resolver ListHandlerMethodArgumentResolver
Next is the custom parameter parser, which needs to implement the interface HandlerMethodArgumentResolver
Public class ListHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {@ Override public boolean supportsParameter (MethodParameter parameter) {return parameter.hasParameterAnnotation (ListParam.class);} @ Override public Object resolveArgument (MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {ListParam param = parameter.getParameterAnnotation (ListParam.class) If (param = = null) {throw new IllegalArgumentException ("Unknown parameter type [" + parameter.getParameterType (). GetName () + "]);} String name =" .equals IgnoreCase (param.name ())? Param.value (): param.name (); if (".equalsIgnoreCase (name)) {name = parameter.getParameter (). GetName ();} String ans = webRequest.getParameter (name); if (ans = = null) {return null;} String [] cells = StringUtils.split (ans,", "); return Arrays.asList (cells);}}
There are two ways:
SupportsParameter is used to indicate whether this parameter parser is applicable.
The implementation is also relatively simple, that is, to see if there are ListParam annotations defined earlier on the parameters.
The resolveArgument method is to realize the concrete logic of rough conversion of http parameters to target method parameters.
The above is mainly to demonstrate the process of custom parameter parser, the implementation is relatively simple, only List is supported by default
3. Register
Although the above implements a custom parameter parser, we need to register it with HandlerMethodArgumentResolver to take effect. A simple method is as follows
@ SpringBootApplicationpublic class Application extends WebMvcConfigurationSupport {@ Override protected void addArgumentResolvers (List argumentResolvers) {argumentResolvers.add (new ListHandlerMethodArgumentResolver ());} public static void main (String [] args) {SpringApplication.run (Application.class);}} 4. test
To verify our custom parameter resolver ok, we open two comparative rest services
@ RestController@RequestMapping (path = "get") public class ParamGetRest {/ * Custom Parameter Parser * * @ param names * @ param age * @ return * / @ GetMapping (path = "self") public String selfParam (@ ListParam (name = "names") List names, Integer age) {return names + "| age=" + age } @ GetMapping (path = "self2") public String selfParam2 (List names, Integer age) {return names + "| age=" + age;}}
The demonstration demo is as follows. Those with ListParam annotations can be parsed normally, and those without annotations will throw an exception.
At this point, I believe you have a deeper understanding of "how to customize the parameter parser for SpringBoot". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.