本篇文章为大家展示了如何进行SpringMVC在Controller层方法的参数解析,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
使用版本:
spring-boot: 2.1.6.RELEASE
sping: 5.1.8.RELEASE
java: openjdk 11.0.13
为了能够实现自定义参数解析器,只需要实现 HandlerMethodArgumentResolver 并将添加到 WebMvcConfigurer#addArgumentResolvers 即可。
下面以添加一个获取请求头的 client-type 参数为例进行是实现。定义注解 @ClientTypeMark 以及enum ClientType ,用于注入header中的值。
@Target({ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ClientTypeMark { }
public enum ClientType { WEB, MOBILE, UNKNOWN ; }
最终实现的效果为在Controller的方法中,可以按照如下实现使用。
@RestController @RequestMapping("/client") public class ClientTypeEndpoint { @GetMapping("/cur") public ClientType getCurClientType(@ClientTypeMark ClientType clientType) { return clientType; } }
按照如下方法实现 HandlerMethodArgumentResolver ,用于解析header中的 client-type 并转化为 ClientType 。
package io.github.donespeak.springbootsamples.web.common; import org.apache.commons.lang3.StringUtils; import org.springframework.core.MethodParameter; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.ModelAndViewContainer; public class CurClientTypeMethodArgumentResolver implements HandlerMethodArgumentResolver { private final String[] CLIENT_TYPE_HEADER_NAMES = {"client-type", "CLIENT-TYPE", "Client-Type"}; // 选择要被注入的参数:判断参数是否符合解析的条件 @Override public boolean supportsParameter(MethodParameter param) { return param.hasParameterAnnotation(ClientTypeMark.class) && ClientType.class.isAssignableFrom(param.getParameterType()); } // 返回值将被注入到被选中参数中 @Override public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception { String clientType = null; for (String clientTypeHeader: CLIENT_TYPE_HEADER_NAMES) { clientType = nativeWebRequest.getHeader(clientTypeHeader); if (StringUtils.isNotBlank(clientType)) { break; } } try { return StringUtils.isBlank(clientType) ? ClientType.UNKNOWN : ClientType.valueOf(clientType.toUpperCase()); } catch (Exception e) { return ClientType.UNKNOWN; } } }
为了使得配置能够生效,可以按照如下的方法添加解析器。
@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { // 解析@CurUserId注解的参数 argumentResolvers.add(new CurClientTypeMethodArgumentResolver()); } }
至此,自定义参数解析器的工作就完成了。
当你完成上面的自定义解析器的时候,大体就能知道Spring在Controller层的其他参数解析都是怎么实现的了。
如下是Spring Mvc默认的一些参数解析器。
package org.springframework.web.servlet.mvc.method.annotation; public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter implements BeanFactoryAware, InitializingBean { ... /** * Return the list of argument resolvers to use including built-in resolvers * and custom resolvers provided via {@link #setCustomArgumentResolvers}. */ private List<HandlerMethodArgumentResolver> getDefaultArgumentResolvers() { List<HandlerMethodArgumentResolver> resolvers = new ArrayList<>(); // Annotation-based argument resolution // 解析:@RequestParam(required = false) resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), false)); // 解析:@RequestParam Map resolvers.add(new RequestParamMapMethodArgumentResolver()); // 解析:@PathVariable resolvers.add(new PathVariableMethodArgumentResolver()); // 解析:@PathVariable Map resolvers.add(new PathVariableMapMethodArgumentResolver()); // 解析:@MatrixVariable resolvers.add(new MatrixVariableMethodArgumentResolver()); // 解析:@MatrixVariable Map resolvers.add(new MatrixVariableMapMethodArgumentResolver()); // 解析:@ModelAttribute(required = false) resolvers.add(new ServletModelAttributeMethodProcessor(false)); // 解析:@RequestBody resolvers.add(new RequestResponseBodyMethodProcessor(getMessageConverters(), this.requestResponseBodyAdvice)); // 解析:@RequestPart resolvers.add(new RequestPartMethodArgumentResolver(getMessageConverters(), this.requestResponseBodyAdvice)); // 解析:@RequestHeader resolvers.add(new RequestHeaderMethodArgumentResolver(getBeanFactory())); // 解析:@RequestHeader Map resolvers.add(new RequestHeaderMapMethodArgumentResolver()); // 解析:@CookieValue resolvers.add(new ServletCookieValueMethodArgumentResolver(getBeanFactory())); // 解析:@Value resolvers.add(new ExpressionValueMethodArgumentResolver(getBeanFactory())); // 解析:@SessionAttribute resolvers.add(new SessionAttributeMethodArgumentResolver()); // 解析:@RequestAttribute resolvers.add(new RequestAttributeMethodArgumentResolver()); // Type-based argument resolution // 解析:WebRequest、ServletRequest、MultipartRequest、HttpSession、 // Principal、Locale、TimeZone、java.time.ZoneId、InputStream // java.io.Reader、org.springframework.http.HttpMethod resolvers.add(new ServletRequestMethodArgumentResolver()); // 解析:ServletResponse、OutputStream、Writer resolvers.add(new ServletResponseMethodArgumentResolver()); // 解析:@HttpEntity、@RequestEntity resolvers.add(new HttpEntityMethodProcessor(getMessageConverters(), this.requestResponseBodyAdvice)); // 解析:RedirectAttributes resolvers.add(new RedirectAttributesMethodArgumentResolver()); // 解析:org.springframework.ui.Model, 值为ModelAndViewContainer#getModel resolvers.add(new ModelMethodProcessor()); // 解析:Map, 值为ModelAndViewContainer#getModel resolvers.add(new MapMethodProcessor()); // 解析:org.springframework.validation.Errors resolvers.add(new ErrorsMethodArgumentResolver()); // 解析:org.springframework.web.bind.support.SessionStatus resolvers.add(new SessionStatusMethodArgumentResolver()); // 解析:UriComponentsBuilder 或者 ServletUriComponentsBuilder resolvers.add(new UriComponentsBuilderMethodArgumentResolver()); // Custom arguments if (getCustomArgumentResolvers() != null) { resolvers.addAll(getCustomArgumentResolvers()); } // Catch-all // 解析:@RequestParam(required = true) resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), true)); // 解析:@ModelAttribute(required = true) resolvers.add(new ServletModelAttributeMethodProcessor(true)); return resolvers; } ... }
调整解析器的顺序
在一次使用spring security的开发中,定义的 UserDetials 实现类在实现 UserDetails 的同时还是实现了一个 Account 接口,在使用时,希望实现如下的效果。
public void doSomething(@AuthenticationPrincipal Account accout) {}
但因为同时使用了,spring-data,spring-data提供的 ProxyingHandlerMethodArgumentResolver 会在 AuthenticationPrincipalArgumentResolver 前面对Account进行注入处理。ProxyingHandlerMethodArgumentResolver 会拦截掉所有非org.springframework中定义的 接口 ,并尝试赋值。为了能够正常赋值给Account,需要调整两者的位置。实现如下:
import java.util.LinkedList; import java.util.List; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver; import org.springframework.stereotype.Component; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; /** * 将 AuthenticationPrincipalArgumentResolver 移到最前面,如果不做调整, * 会因为ProxyingHandlerMethodArgumentResolver在AuthenticationPrincipalArgumentResolver前面, * 导致 @AuthenticationPrincipal Account account 无法注入 */ public class ArgumentResolverBeanPostProcessor implements BeanPostProcessor { private static final String BEAN_REQUEST_MAPPING_HANDLER_ADAPTER = "requestMappingHandlerAdapter"; @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (beanName.equals(BEAN_REQUEST_MAPPING_HANDLER_ADAPTER)) { RequestMappingHandlerAdapter adapter = (RequestMappingHandlerAdapter)bean; List<HandlerMethodArgumentResolver> argumentResolvers = adapter.getArgumentResolvers(); LinkedList<HandlerMethodArgumentResolver> resolversAdjusted = new LinkedList<>(argumentResolvers); argumentResolvers.stream().forEach(r -> { if (AuthenticationPrincipalArgumentResolver.class.isInstance(r)) { resolversAdjusted.addFirst(r); } else { resolversAdjusted.add(r); } }); adapter.setArgumentResolvers(resolversAdjusted); } return bean; } }
上述内容就是如何进行SpringMVC在Controller层方法的参数解析,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。