SpringBoot-web综合
Posted swpCode
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot-web综合相关的知识,希望对你有一定的参考价值。
- 自定义Filter
public class MyFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("filter init"); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; String uri = request.getRequestURI(); System.out.println("filter uri : " + uri); filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { System.out.println("filter destroy"); } }
- 自定义Listener
/** * 描述: * 1.ServletContextListener -- 监听servletContext对象的创建以及销毁 * 2.HttpSessionListener -- 监听session对象的创建以及销毁 * 3.ServletRequestListener -- 监听request对象的创建以及销毁 * 4.ServletContextAttributeListener -- 监听servletContext对象中属性的改变 * 5.HttpSessionAttributeListener --监听session对象中属性的改变 * 6.ServletRequestAttributeListener --监听request对象中属性的改变 * @outhor ios * @create 2019-01-03 3:00 PM */ public class MyListener implements ServletRequestListener { @Override public void requestDestroyed(ServletRequestEvent sre) { System.out.println("---------------------------->请求销毁"); } @Override public void requestInitialized(ServletRequestEvent sre) { System.out.println("---------------------------->请求创建"); } }
- 自定义interceptor
public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("拦截器 -- 请求处理之前"); return false; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("拦截器 -- 请求处理之后,视图渲染之前"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("拦截器 -- 请求处理之后,视图渲染之后"); } }
- 注册自定义的Filter,Listener,Intercetor
@Configuration public class WebConfig implements WebMvcConfigurer { @Bean public FilterRegistrationBean filterRegistrationBean(){ FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(new MyFilter()); bean.setName("MyFilter"); bean.addUrlPatterns("/*"); return bean; } @Bean public ServletListenerRegistrationBean listenerRegistrationBean(){ ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean(); bean.setListener(new MyListener()); return bean; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**"); } }
以上是关于SpringBoot-web综合的主要内容,如果未能解决你的问题,请参考以下文章