一、如何定制和修改Servlet容器的相关配置
修改和server有关的配置(ServerProperties)
properties
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
java
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 Servlet");
}
}
MyServerConfig
java
@Configuration
public class MyServerConfig {
/*
* 注册三大组件
* */
//Servlet
@Bean
public ServletRegistrationBean myServlet(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean(new
MyServlet(),"/myServlet");
return registrationBean;
}
}
运行:
2.Filter
MyFilter
java
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...");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
MyServerConfig
java
@Configuration
public class MyServerConfig {
/*
* 注册三大组件
* */
//Filter
@Bean
public FilterRegistrationBean myFilter(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new MyFilter());
registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
return registrationBean;
}
}
运行:
3.Listener
MyListener
java
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("contextInitialized ...启动");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("contextDestroyed ...销毁");
}
}
MyServerConfig
java
@Configuration
public class MyServerConfig {
/*
* 注册三大组件
* */
//Listener
@Bean
public ServletListenerRegistrationBean myListener(){
ServletListenerRegistrationBean<MyListener> registrationBean = new
ServletListenerRegistrationBean<>(new MyListener());
return registrationBean;
}
}
运行: