1.写一个servlet 类
package sprintbootstudy.springbootquickstart.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class Myservlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
再写一个配置类 @Configuration 注册三大组件
Servlet Filter Listener
ServletRegistrationBean:
package sprintbootstudy.springbootquickstart.config;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import sprintbootstudy.springbootquickstart.servlet.Myservlet;
@Configuration
public class myserverConfig {
//注册三大组件
@Bean //加在容器中
public ServletRegistrationBean myservlet(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean(new Myservlet(),"/myservlet");
return registrationBean;
}
}
Filter:拦截器
@Bean //filter是拦截器
public FilterRegistrationBean myFilter(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new MyFilter());
registrationBean.setUrlPatterns(Arrays.asList("/hello","/myservlet"));
return registrationBean;
}
package sprintbootstudy.springbootquickstart.controller;
import javax.servlet.*;
import java.io.IOException;
public class MyFilter implements Filter { //注意 这个是javax.servlet下的包
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("MyFilter process....");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
Listener: 监听web销毁或者是生成的
@Bean
public ServletListenerRegistrationBean servletListenerRegistrationBean() {
ServletListenerRegistrationBean<MyListener> servletListenerRegistrationBean = new ServletListenerRegistrationBean<MyListener>(new MyListener());
return servletListenerRegistrationBean;
}
package sprintbootstudy.springbootquickstart.controller;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyListener implements ServletContextListener { //重写启动和销毁的方法
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("contextInitialized....web 启动");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("contextDestroyed...web 销毁");
}
}
Servlet 容器可以切换 不只是有Tomcat