Spring地区语言扩展 & 创建filter
Spring地区语言扩展
- LocaleResolver:从请求参数中解析地区、语言参数,并设置到上下文
- 多语言相关扩展点:MessageSourceSupport、AbstractMessageSource、ReloadableResourceBundleMessageSource、MessageSource
创建Filter
- 继承 GenericFilterBean 或者 OncePerRequestFilter 、Filter
- 通过创建bean或者使用 @Webfilter 注解声明过滤器
@Bean
public FilterRegistrationBean<CustomFilter> loggingFilter(){
FilterRegistrationBean<CustomFilter> registrationBean
= new FilterRegistrationBean<>();
registrationBean.setFilter(new CustomFilter());
registrationBean.addUrlPatterns("/api/*");
//.. 其他设置项
return registrationBean;
}
或者
@WebFilter:在java servlet 层面声明filter,并指定拦截的请求
@Component:将其声明为Spring Bean,默认拦截所有请求,需要在 filter() 中根据实际情况拦截
@WebFilter(urlPatterns = {"/api/*"})
public class CustomFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("CustomFilter initialized.");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("Before processing the request.");
chain.doFilter(request, response);
System.out.println("After processing the request.");
}
@Override
public void destroy() {
System.out.println("CustomFilter destroyed.");
}
}
创建拦截器
- 实现接口 HandlerInterceptor
- 实现类注册到Spring中,WebMvcConfigurer这个接口是SpringMVC中一个重要的扩展接口。
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CusomInterceptor()).addPathPatterns("/api/*");
}
}