Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The HandlerMethodArgumentResolver interface in SpringMVC implements custom parameter type resolution.

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "HandlerMethodArgumentResolver interface in SpringMVC to achieve custom parameter type resolution", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor to take you to learn "the HandlerMethodArgumentResolver interface in SpringMVC to achieve custom parameter type resolution"!

HandlerMethodArgumentResolver interface

The HandlerMethodArgumentResolver interface looks strange, but in fact, we come into contact with it directly or indirectly in many places in SpringMVC.

For example:

@ RequestParam parses RequestParamMethodArgumentResolver (the default parser for the base type)

@ PathVariable parses PathVariableMethodArgumentResolver

@ RequestBody parses RequestResponseBodyMethodProcessor

@ CookieValue parses ServletCookieValueMethodArgumentResolver...

By looking at the source code of SpringMVC, you can see the following code snippet, which is the default implementation of all HandlerMethodArgumentResolver when SpringMVC is initialized

/ / org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapterprivate List getDefaultArgumentResolvers () {List resolvers = new ArrayList (); / / Annotation-based argument resolution resolvers.add (new RequestParamMethodArgumentResolver (getBeanFactory (), false)); resolvers.add (new RequestParamMapMethodArgumentResolver ()); resolvers.add (new PathVariableMethodArgumentResolver ()); resolvers.add (new PathVariableMapMethodArgumentResolver ()); resolvers.add (new MatrixVariableMethodArgumentResolver ()); resolvers.add (new MatrixVariableMapMethodArgumentResolver ()); resolvers.add (new ServletModelAttributeMethodProcessor (false)) Resolvers.add (new RequestResponseBodyMethodProcessor (getMessageConverters (), this.requestResponseBodyAdvice)); resolvers.add (new RequestPartMethodArgumentResolver (getMessageConverters (), this.requestResponseBodyAdvice)); resolvers.add (new RequestHeaderMethodArgumentResolver (getBeanFactory (); resolvers.add (new RequestHeaderMapMethodArgumentResolver ()); resolvers.add (new ServletCookieValueMethodArgumentResolver (getBeanFactory (); resolvers.add (new ExpressionValueMethodArgumentResolver (getBeanFactory (); resolvers.add (new SessionAttributeMethodArgumentResolver ()); resolvers.add (new RequestAttributeMethodArgumentResolver ()) / / Type-based argument resolution resolvers.add (new ServletRequestMethodArgumentResolver ()); resolvers.add (new ServletResponseMethodArgumentResolver ()); resolvers.add (new HttpEntityMethodProcessor (getMessageConverters (), this.requestResponseBodyAdvice)); resolvers.add (new RedirectAttributesMethodArgumentResolver ()); resolvers.add (new ModelMethodProcessor ()); resolvers.add (new MapMethodProcessor ()); resolvers.add (new ErrorsMethodArgumentResolver ()); resolvers.add (new SessionStatusMethodArgumentResolver ()); resolvers.add (new UriComponentsBuilderMethodArgumentResolver ()) / / Custom arguments if (getCustomArgumentResolvers ()! = null) {resolvers.addAll (getCustomArgumentResolvers ());} / / Catch-all resolvers.add (new RequestParamMethodArgumentResolver (getBeanFactory (), true)); resolvers.add (new ServletModelAttributeMethodProcessor (true)); return resolvers;}

The HandlerMethodArgumentResolver interface has two methods, one is used to determine whether the parameter type is supported, and the other is the concrete implementation of parsing.

Public interface HandlerMethodArgumentResolver {/ / returns whether the parameter boolean supportsParameter (MethodParameter parameter) is supported; / / returns the parsed parameter value @ Nullable Object resolveArgument (MethodParameter parameter, @ Nullable ModelAndViewContainer mavContainer, NativeWebRequest webRequest, @ Nullable WebDataBinderFactory binderFactory) throws Exception;} usage scenario

The main usage scenario of this interface is to implement custom parameter injection. For example, in many projects where front and rear ends are separated, instead of using Session, we maintain a token to implement state management.

At this time, if we need to obtain user data and operate normally, we may need to obtain token manually and then query user data.

For example, in the following example, we get the token data from Header, then query the user ID from Redis, and then query the basic user information from the database.

@ PostMapping ("get-user-info") public UserInfo getUserInfo (@ RequestHeader String token) {/ / pseudo code Long userId = redisClient.get (token); UserInfo useInfo = userDao.getById (userId); return userInfo;}

There is no problem with writing this way, but in the actual project, we may need to use some basic information of the user in many places, and it is very tedious to code it manually every time.

We use the HandlerMethodArgumentResolver interface to implement

/ / 1. Implement the HandlerMethodArgumentResolver interface public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {private final RedisClient redisClient; private final UserDao userDao; public UserInfoArgumentResolver (RedisClient redisClient, UserDao userDao) {this.redisClient = redisClient; this.userDao = userDao;} @ Override public boolean supportsParameter (MethodParameter parameter) {return UserInfo.class.isAssignableFrom (parameter.getParameterType ()) } @ Override public Object resolveArgument (MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {HttpServletRequest nativeRequest = (HttpServletRequest) webRequest.getNativeRequest (); String token = nativeRequest.getHeader ("token"); Long userId = redisClient.get (token); UserInfo useInfo = userDao.getById (userId); return userInfo;} / / 2. Add to the configuration @ Configuration@EnableWebMvcpublic class FastMvcConfiguration implements WebMvcConfigurer {@ Autowrite UserDao userDao; @ Autowrite RedisClient redisClient; @ Override public void addArgumentResolvers (List resolvers) {resolvers.add (new UserInfoArgumentResolver (redisClient, userDao));}} / / 3. Use @ RestControllerpublic class UserInfoController {@ PostMapping ("get-user-info") public UserInfo getUserInfo (UserInfo userInfo) {return userInfo;} @ PostMapping ("say-hello") public String sayHello (UserInfo userInfo) {return "hello" + userInfo.getNickName ();} in Controller

After adding the UserInfoArgumentResolver interpreter, when we need to use UserInfo, we only need to use the specified type to get it, and we don't need to do anything else

At this point, I believe you have a deeper understanding of "HandlerMethodArgumentResolver interface in SpringMVC to achieve custom parameter type resolution". 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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report