- 如何定制和修改Servlet容器的相关配置
a. 修改和Server有关的配置(ServerProperties)
server.port=8084
server.servlet.context-path=/crud
server.tomcat.uri-encoding=UTF-8
# 通用的servlet容器配置
server.xxx
// tomcat的配置
server.tomcat.xxx
- 注册Servlet,Filter,Listener
ServletRegistrationBean
FilterRegistrationBean
ServletListenerRegistrationBean
@Configuration
public class myMVConfig implements WebMvcConfigurer{
// 注册servlet
@Bean
public ServletRegistrationBean<Servlet> myServlet(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(new MyServlet(), "/myServlet");
registrationBean.setLoadOnStartup(1);
return registrationBean;
}
// 注册监听器
@Bean
public ServletListenerRegistrationBean<MyListener> myLister(){
ServletListenerRegistrationBean<MyListener> listener = new ServletListenerRegistrationBean<>();
listener.setListener(new MyListener());
return listener;
}
// 注册过滤器
@Bean
public FilterRegistrationBean<MyFilter> myFilter(){
FilterRegistrationBean<MyFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new MyFilter());
registrationBean.setUrlPatterns(Arrays.asList("/main.html"));
return registrationBean;
}
myServlet
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("这是我自己的servlet");
}
}
myFIlter
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("执行前");
chain.doFilter(request,response);
System.out.println("执行后");
}
@Override
public void destroy() {
}
}
myListener
public class MyListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("web容器启动了");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("web容器停止了");
}
}
- 替换为其他嵌入式Servlet容器
默认支持
Tomcat(默认使用)
Jetty
Undertow
切换其他容器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<artifactId>spring-boot-starter-jetty</artifactId>
<groupId>org.springframework.boot</groupId>
</dependency>