-
修改和 server 相关的配置(ServerProperties):
server.port=8081 server.context‐path=/tx server.tomcat.uri‐encoding=UTF‐8
- 注册 Servlet 三大组件:Servlet、Fileter、Listener
- SpringBoot 默认是以 jar 包的方式启动嵌入式的 Servlet 容器来启动 SpringBoot 的 web应用,没有外部文件
- Servlet:
//注册三大组件 @Bean public ServletRegistrationBean myServlet(){ ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet"); return registrationBean; }
- FilterRegisttratinBean:
@Bean public FilterRegistrationBean myFilter(){ FilterRegistrationBean registrationBean = new FilterRegistrationBean(); registrationBean.setFilter(new MyFilter()); registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet")); return registrationBean; }
- SErvletListenerRegistrationBean:
@Bean public ServletListenerRegistrationBean myListener(){ ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener()); return registrationBean; }
- SpringBoot 帮我们自动整合 SpringMVC 的时候,自动的注册 SpringMVC 的前端控制器:DispatherServlet
- 在 DispatherServletAutoConfiguration 中:
@Bean(name = DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME) @ConditionalOnBean(value = DispatcherServlet.class, name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME) public ServletRegistrationBean dispatcherServletRegistration( DispatcherServlet dispatcherServlet) { ServletRegistrationBean registration = new ServletRegistrationBean( dispatcherServlet, this.serverProperties.getServletMapping()); //默认拦截: / 所有请求;包静态资源,但是不拦截jsp请求; /*会拦截jsp //可以通过server.servletPath来修改SpringMVC前端控制器默认拦截的请求路径 registration.setName(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME); registration.setLoadOnStartup( this.webMvcProperties.getServlet().getLoadOnStartup()); if (this.multipartConfig != null) { registration.setMultipartConfig(this.multipartConfig); } return registration; }
使用外置的 Servlet 容器:
- 嵌入式 Servlet 容器:应用打成可执行的 jar 包
- 优点:简单、便携
- 缺点:默认不支持 JSP、优化定制比较复杂
- 外置的 Servlet 容器:外面安装 Tomcat ,应用打包方式为 war 包
-
步骤:
- 创建一个 war 项目
- 将嵌入式的 Tomcat 指定为 provided
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring‐boot‐starter‐tomcat</artifactId> <scope>provided</scope> </dependency>
- 配置项目的目录结构:
- 部署 Tomcat
- 必须编写一个 SpringBootSerbletInitializer 的子类,并调用 configure 方法
public class ServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(DemoApplication.class); } }
- 启动服务即可使用
-
原理:
- jar 包:执行 SpringBoot 主类的 main 方法,启动 IOC 容器,创建嵌入式的 Servlet 容器
- war 包:启动服务器,服务器启动 SpringBoot 应用[ SpringBootServletInitializer ],启动 IOC 容器