一、如何定制和修改Servlet容器的相关配置
修改和server有关的配置(ServerProperties)
server.port=8081
server.context‐path=/tx
server.tomcat.uri-encoding=UTF-8
二、注册servlet三个组件【Servlet、Filter、Listener】
由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml文件。之前这三个都是配置在web.xml中的,现在:
1.Sevlet
MyServlet
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 {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.getWriter().print("Hello Servlet");}
}
MyServerConfig
@Configuration
public class MyServerConfig {/** 注册三大组件* *///Servlet@Beanpublic ServletRegistrationBean myServlet(){ServletRegistrationBean registrationBean = new ServletRegistrationBean(newMyServlet(),"/myServlet");return registrationBean;}
}
运行:
2.Filter
MyFilter
public class MyFilter implements Filter {public MyFilter() {super();}@Overridepublic void init(FilterConfig filterConfig) throws ServletException {System.out.println("myFilter初始化...");}@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {System.out.println("MyFilter...");filterChain.doFilter(servletRequest, servletResponse);}@Overridepublic void destroy() {}
}
MyServerConfig
@Configuration
public class MyServerConfig {/** 注册三大组件* *///Filter@Beanpublic FilterRegistrationBean myFilter(){FilterRegistrationBean registrationBean = new FilterRegistrationBean();registrationBean.setFilter(new MyFilter());registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));return registrationBean;}}
运行:
3.Listener
MyListener
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;public class MyListener implements ServletContextListener {@Overridepublic void contextInitialized(ServletContextEvent servletContextEvent) {System.out.println("contextInitialized ...启动");}@Overridepublic void contextDestroyed(ServletContextEvent servletContextEvent) {System.out.println("contextDestroyed ...销毁");}
}
MyServerConfig
@Configuration
public class MyServerConfig {/** 注册三大组件* *///Listener@Beanpublic ServletListenerRegistrationBean myListener(){ServletListenerRegistrationBean<MyListener> registrationBean = newServletListenerRegistrationBean<>(new MyListener());return registrationBean;}}
运行: