1、使用Servlet API
1. @ServletComponentScan(basePackages = "com.flyyant.demo.uploadfile");制定原生Servlet组件都放在那里
2. @WebServlet(urlPatterns = "/my");效果:直接响应,没有Spring的拦截器拦截
3. @WebServlet(urlPatterns = "/my")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("66666");
}
}
4. @WebFilter(urlPatterns = {"/css/*","/images/*"}) //my,指定拦截的东西
@Slf4j
@WebFilter(urlPatterns = {"/css/*","/images/*"}) //my,指定拦截的东西
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
log.info("初始化");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
log.info("开始工作");
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
log.info("销毁");
}
}
5. @WebListener
@Slf4j
@WebListener
public class MyListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
log.info("初始化");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
log.info("销毁");
}
}
推荐可以这种方式:
扩展: DispatchServlet如何注册进来
1. 容器中自动配置了DispatchServlet属性绑定到WebMvcProperties;对应的配置文件项是spring.mvc
2. 通过ServletRegistrationBean把DispatchServlet配置进来。
默认映射的是/路径
3. 在yml文件中配置
Spring:
Mvc:
Servlet:
Path: /mvc/
Tomcat-Servlet;
多个Servlet都能处理到同一层路径,精确优先原则
2、 使用RegistrationBean
ServletRegistrationBean
FilterRegistrationBean
ServletListenerRegistrationBean
使用: (不需要在每个自定义原生类上加)
原生注解如图
/**
* 1. MyServlet --> /my
* 2. DispatcherServlet --> /
*/
@Configuration //(proxyBeanMethods = false):不写的原因,重复调用新建,容器中会有冗余;默认为true,表示保证以来的组件始终是单实例的
public class MyRegisterConfig {
@Bean
public ServletRegistrationBean myServlet(){
MyServlet myServlet = new MyServlet();
return new ServletRegistrationBean(myServlet,"/my","/my02");
}
@Bean
public FilterRegistrationBean myFilter(){
MyFilter myFilter = new MyFilter();
// return new FilterRegistrationBean(myFilter,myServlet());
FilterRegistrationBean<MyFilter> myFilterFilterRegistrationBean = new FilterRegistrationBean<>(myFilter);
myFilterFilterRegistrationBean.setUrlPatterns(Arrays.asList("/my","/css/*"));
return myFilterFilterRegistrationBean;
}
@Bean
public ServletListenerRegistrationBean myListener(){
MyListener myListener = new MyListener();
return new ServletListenerRegistrationBean(myListener);
}
}