SpringBoot自定义

2020-06-08 16:11:56 浏览数 (1)

自定义 Servlet

代码语言:javascript复制
 编写 Servlet
public class ServletTest extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		resp.getWriter().write("自定义 Servlet");
	}
	
}

注册 Servlet
将 Servelt 注册成 Bean。在上文创建的 WebConfig 类中添加如下代码:
@Bean
public ServletRegistrationBean servletRegistrationBean() {
    return new ServletRegistrationBean(new ServletTest(),"/servletTest");
}

结果如下:

自定义过滤器/第三方过滤器

代码语言:javascript复制
编写过滤器
public class TimeFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("=======初始化过滤器=========");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {

		long start = System.currentTimeMillis();

		filterChain.doFilter(request, response);

		System.out.println("filter 耗时:"   (System.currentTimeMillis() - start));

	}

	@Override
	public void destroy() {
		System.out.println("=======销毁过滤器=========");
	}

}

 注册过滤器
要是该过滤器生效,有两种方式:
1.使用 @Component 注解
2.添加到过滤器链中,此方式适用于使用第三方的过滤器。将过滤器写到 WebConfig 类中,如下:
@Bean
public FilterRegistrationBean timeFilter() {
	FilterRegistrationBean registrationBean = new FilterRegistrationBean();
	
	TimeFilter timeFilter = new TimeFilter();
	registrationBean.setFilter(timeFilter);
	
	List<String> urls = new ArrayList<>();
	urls.add("/*");
	registrationBean.setUrlPatterns(urls);
	
	return registrationBean;
}

结果如下:

自定义监听器

代码语言:javascript复制
编写监听器
public class ListenerTest implements ServletContextListener {

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("监听器初始化...");
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {

	}

}

注册监听器
注册监听器为 Bean,在 WebConfig 配置类中添加如下代码:
@Bean
public ServletListenerRegistrationBean<ListenerTest> servletListenerRegistrationBean() {
    return new ServletListenerRegistrationBean<ListenerTest>(new ListenerTest());
}

针对自定义 Servlet、Filter 和 Listener 的配置,还有另一种方式:
@SpringBootApplication
public class SpringbootWebApplication implements ServletContextInitializer {
    
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
    	// 配置 Servlet
        servletContext.addServlet("servletTest",new ServletTest())
        			  .addMapping("/servletTest");
        // 配置过滤器
        servletContext.addFilter("timeFilter",new TimeFilter())
        			  .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST),true,"/*");
        // 配置监听器
        servletContext.addListener(new ListenerTest());
    }

	public static void main(String[] args) {
		SpringApplication.run(SpringbootWebApplication.class, args);
	}
}

结果如下:

自定义拦截器

代码语言:javascript复制
编写拦截器
使用 @Component 让 Spring 管理其生命周期:
@Component
public class TimeInterceptor implements HandlerInterceptor {
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		System.out.println("========preHandle=========");
		System.out.println(((HandlerMethod)handler).getBean().getClass().getName());
		System.out.println(((HandlerMethod)handler).getMethod().getName());
		
		request.setAttribute("startTime", System.currentTimeMillis());
		
		return true;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
			throws Exception {

		System.out.println("========postHandle=========");
		Long start = (Long) request.getAttribute("startTime");
		System.out.println("耗时:" (System.currentTimeMillis() - start));
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception)
			throws Exception {

		System.out.println("========afterCompletion=========");
		Long start = (Long) request.getAttribute("startTime");
		System.out.println("耗时:" (System.currentTimeMillis() - start));
		
		System.out.println(exception);
	}

}

注册拦截器
编写拦截器后,我们还需要将其注册到拦截器链中,如下配置:
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
	
	@Autowired
	private TimeInterceptor timeInterceptor;
	

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(timeInterceptor);
	}

}

请求一个 controller ,结果如下:

0 人点赞