您好,登錄后才能下訂單哦!
本篇文章為大家展示了如何進行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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。