由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml文件。
注册三大组件,class MyServlet()/class MyListener/ class MyFilter 需要自己亲自编写!!
1. class MyServlet
package com.szs.springboot04.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 {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().print("Hello MyServlet!!!");
}
}
ServletRegistrationBean 注册
@Configuration
public class MyServerConfig {
/**
* 注册三大组件
*/
@Bean
public ServletRegistrationBean myServlet(){
ServletRegistrationBean registrationBean =
new ServletRegistrationBean(new MyServlet(),"/myServlet");
registrationBean.setLoadOnStartup(1);
return registrationBean;
}
效果展示
2.class MyFilter implements Filter
import javax.servlet.*;
import java.io.IOException;
public class MyFilter implements Filter {
public MyFilter() {
super();
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("myFilter正在初始化...");
}
@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() {
}
}
FilterRegistrationBean 注册
@Configuration
public class MyServerConfig {
@Bean
public FilterRegistrationBean myFilter(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new MyFilter());
registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
return registrationBean;
}
3.class MyListener implements ServletContextListener
public class MyListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("contextInitialized ...web应用启动");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("contextDestroyed... web项目已经销毁");
}
}
ServletListenerRegistrationBean myListener()
@Configuration
public class MyServerConfig {
@Bean
public ServletListenerRegistrationBean myListener(){
return new ServletListenerRegistrationBean<>(new MyListener());
}