1-自定义servlet组件
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("hello servlet success...");
}
}
2-自定义listener组件
public class MyListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("springboot.servlet启动");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("springboot.servlet销毁");
}
}
3-自定义Filter
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("filter 初始化操作");
}
@Override
public void destroy() {
System.out.println("filter销毁");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("myfilter 过滤完成");
filterChain.doFilter(servletRequest,servletResponse);
}
}
4-配置类(分别注册三大组件@Bean添加到容器内)
@Configuration
public class MyServletConfig {
@Bean
public ServletRegistrationBean helloServlet(){
ServletRegistrationBean bean
= new ServletRegistrationBean(new HelloServlet(), "/hello");
bean.setLoadOnStartup(1);
return bean;
}
@Bean
public FilterRegistrationBean myFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new MyFilter());
bean.setUrlPatterns(Arrays.asList("/hello"));
return bean;
}
@Bean
public ServletListenerRegistrationBean myListener(){
ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean(new MyListener());
return bean;
}
}