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

Common configuration methods of SpringMVC under Springboot

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly explains "the common configuration methods of SpringMVC under Springboot". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "the common configuration methods of SpringMVC under Springboot".

I. Preface

The configuration of SpringMVC in Sprinboot mainly inherits WebMvcConfigurerAdapter (version 1.x) or WebMvcConfigurationSupport (version 2.x). This time, we mainly introduce some common configurations of web applications.

Start configuration (1) configure parameter parser

The role of the parameter parser, generally speaking, the role of the parameter parser is to map the parameters in the request to the parameters of our Controller method. For example, through the parameter parser, we can process the token parameters passed from the front end, extract the user information from the redis, and map directly to a userInfo object, and then the parameters of the Controller method are directly UserInfo objects. How to use Le? Here is a simple example, where only pseudocode is posted:

First we create a parser class and implement the HandlerMethodArgumentResolver interface.

Public class TokenHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {private RedissonClient redissonClient; private UserDao userDao; public TokenHandlerMethodArgumentResolver (RedisClient redisClient, UserDao userDao) {this.redissonClient = redisClient; this.userDao = userDao;} @ Override public boolean supportsParameter (MethodParameter methodParameter) {return User.class.isAssignableFrom (methodParameter.getParameterType ());} @ Override public Object resolveArgument (MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {HttpServletRequest nativeRequest = (HttpServletRequest) nativeWebRequest.getNativeRequest () String token = nativeRequest.getHeader ("token"); RBucket userIdBucket = redissonClient.getBucket (token); if (StringUtils.isNotBlank (userIdBucket.get () {User user = userDao.getById (userIdBucket.get ());} return user;}}

Then create the class MyWebConfig, inherit WebMvcConfigurerAdapter and implement the ApplicationContextAware interface. Why implement ApplicationContextAware is to extract redissonClient and userDao from the IOC container to construct TokenHandlerMethodArgumentResolver.

Public class MyWebConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {private UserDao userDao; private RedissonClient redissonClient; @ Override public void addArgumentResolvers (List argumentResolvers) {argumentResolvers.add (new TokenHandlerMethodArgumentResolver (redissonClient,userDao)); super.addArgumentResolvers (argumentResolvers);} @ Override public void setApplicationContext (ApplicationContext applicationContext) throws BeansException {userDao = applicationContext.getBean (UserDao.class); redissonClient = applicationContext.getBean (RedissonClient.class);}}

As mentioned above, the two most important methods of HandlerMethodArgumentResolver are boolean supportsParameter (MethodParameter methodParameter) and Object resolveArgument (MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory). The former means that if you return ture, you will use the parser for parsing, and the latter will return the processed method parameters. Another key method in the example is the method nativeWebRequest.getNativeRequest (), which is used to get HttpServletRequest through NativeWebRequest.

The logic here is that if one of the parameters is of type User, then get the injection directly through token here. For us, if we need user information, we only need to add a User parameter to the Controller, and we will have it automatically. We don't need to check it ourselves, and we can easily reference the relevant information of the user.

(2) configuration data serialization

There are two ways to serialize configuration data, one is to add Formatter, the other is to add Converter, there is little difference between the two, SpingMVC internal processing of Formatter is also wrapped with a layer of Converter. At the same time, it is worth noting that Formatter and Converter are used when SpringMVC uses the default RequestParamMethodArgumentResolver or ServletModelAttributeMethodProcessor parameter parser. If you customize the parameter parser, the parameters it takes over and the conversion rules are determined by the logic in the custom parameter parser.

In addition, it is mainly applied to form form parameters or query parameter fields, which is not used for Json parameters. The default parameter parser for Json parameters is: RequestResponseBodyMethodProcessor, which is mainly aimed at the method parameters modified by @ RequestBody. The called message converter will use Jackson's ObjectMapper to serialize or deserialize, so if it is JSON parameters, configuring this thing is useless.

1. Configure Formatter

Take configuring a conversion between a LocalDateTime class and a string as an example:

First, create a new class LocalDateTimeFormatter as follows:

Public class LocalDateTimeFormatter implements Formatter {private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern ("yyyy-MM-dd HH:ss:mm"); @ Override public LocalDateTime parse (String s, Locale locale) throws ParseException {return LocalDateTime.parse (s, dateTimeFormatter);} @ Override public String print (LocalDateTime localDateTime, Locale locale) {return dateTimeFormatter.format (localDateTime);}}

The parse method is mainly the logic of converting a string to an object, and the print method is the logic of converting an object into a string.

Then register the Formatter and override the public void addFormatters (FormatterRegistry registry) method in MyWebConfig:

@ Override public void addFormatters (FormatterRegistry registry) {registry.addFormatter (new LocalDateTimeFormatter ()); super.addFormatters (registry);}

In this way, this custom formatter is used by default to convert strings and objects when parameters are not passed by json.

two。 Configure Converter

In general, we use Formatter instead of Converter, and the two functions are similar. The advantage of Converter is that there are two generic parameters that limit the types to be converted and the types to be converted. However, when you look at the source code, you can find that when referencing converter, it seems that the source type to choose which converter is passed in seems to be String (even if the query parameter is a number). It feels that formatter is enough.

The use of converter is very simple. You only need to register a bean that implements org.springframework.core.convert.converter in the spring container. In addition to this form, you can also directly register the ConverterFactory implementation to obtain the factory method Converter getConverter (Class targetType) of converter, which can be used in scenarios of one source type and multiple target types. In addition, there is GenericConverter, which needs to implement the Object convert (@ Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) method, which is used for scenarios of multiple source types and multiple target types, and the returned value is directly the converted value.

(3) configure static resource mapping

The method to configure static resource rewriting is void addResourceHandlers (ResourceHandlerRegistry registry). For example, the rewriting method is:

@ Override public void addResourceHandlers (ResourceHandlerRegistry registry) {registry.addResourceHandler ("/ upload/**") .addResourceLocations ("classpath:/upload/"); super.addResourceHandlers (registry);}

AddResourceHandler ("/ upload/**"). AddResourceLocations ("classpath:/upload/") means that URL: project access url+upload/xxx is mapped to a static resource named XXX in the upload directory under classpath, where the addResourceLocations parameter is a variable-length parameter, which can map multiple paths, or it can be preceded by 'file:', to map any directory on disk. For example, file:/D://upload/, represents the upload directory mapped to disk d.

(IV) configure filter

To add a filter, you only need to register a FilterRegistrationBean class object to the spring container, such as registering a filter that allows cross-domain in the test environment:

Conditional (value = {TestCondition.class}) @ Bean public FilterRegistrationBean corsFilter () {UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource (); CorsConfiguration corsConfiguration = new CorsConfiguration (); corsConfiguration.addAllowedOrigin ("*"); corsConfiguration.addAllowedHeader ("*"); corsConfiguration.addAllowedMethod ("*"); urlBasedCorsConfigurationSource.registerCorsConfiguration ("/ *", corsConfiguration); FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean () FilterRegistrationBean.setOrder (10); filterRegistrationBean.setFilter (new CorsFilter (urlBasedCorsConfigurationSource)); filterRegistrationBean.setName ("corsFilter"); filterRegistrationBean.addUrlPatterns ("/ *"); return filterRegistrationBean;}

The @ Conditional annotation identifies the aplication-test.yml | properties that is referenced in the test environment, where the value should be passed in a Class object of the org.springframework.context.annotation.Condition API implementation class. What is passed in here is TestCondition. The code is as follows:

@ Override public boolean matches (ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {Environment environment = conditionContext.getEnvironment (); String [] activeProfiles = environment.getActiveProfiles (); if (null! = activeProfiles) {for (String x: activeProfiles) {if ("test" .equals (x)) {return true } return false;}

In addition, for custom filters, the general actions are as follows:

Inherit the OncePerRequestFilter abstract class and implement the doFilterInternal method.

Inject this Filter object into filterRegistrationBean and configure other information, such as order, Url that has been filtered.

Such as:

@ Bean public FilterRegistrationBean myFilter () {FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean (); filterRegistrationBean.setFilter (new MyFilter ()); / / the smaller the order, the higher the priority filterRegistrationBean.setOrder (1); filterRegistrationBean.addUrlPatterns ("/ *"); filterRegistrationBean.setName ("myFilter"); return filterRegistrationBean;} (IV) configure the interceptor

The difference between an interceptor and a filter is that the filter has a higher priority than the interceptor. Filter acts in front of Servlet, while Interceptor is a little later than Filter. In addition, Filter cannot use IOC container resources, while Interceptor can. All the functions that can be done by the filter can be done through Interceptor. In general, Interceptor is recommended.

The steps to configure the interceptor are:

1. Create a class that inherits HandlerInterceptorAdapter.

There are three ways to rewrite HandlerInterceptorAdapter without doing any processing before it is rewritten. The three methods are:

/ / execute public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {return true;} / / execute public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {} / / execute public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {} 2 before the business processor processes the request and returns the response. Register interceptor

Override the method void addInterceptors (InterceptorRegistry registry) in the MyWebConfig class, such as:

@ Override public void addInterceptors (InterceptorRegistry registry) {/ / multiple interceptors can form an interceptor chain / / addPathPatterns is used to add interceptor rules / / excludePathPatterns is used to exclude interceptor registry.addInterceptor (new MyInterceptor ()) .addP athPatterns ("/ * *") .intercepdePathPatterns ("/ swagger*/**"); super.addInterceptors (registry);} III. Summary

The above are the common configuration methods of SpringMVC based on Springboot, which can basically meet the configuration needs of common projects, but the rest will not be understood for the time being.

At this point, I believe you have a deeper understanding of the "common configuration methods of SpringMVC under 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.

Share To

Internet Technology

Wechat

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

12
Report