第4章Spring Boot 的Web开发
4.1 静态资源映射规则
总结:
只要静态资源放在类路径下:called /static or /public or /resource or /META-INF/resource
访问:当前根路径/+静态资源名
4.2 enjoy模板引擎
- 将页面保存在templates目录下
- 添加坐标
- 开启配置
- 编写代码
4.3 springMVC
- 请求处理
- 参数绑定
- 常用注解
- 数据传递
- 文件上传
4.4 注册Servlet三大组件 Servlet/Filter/Listener
而由于 Spring Boot 默认是以 jar 包的方式运行嵌入式Servlet容器来启动应用,没有web.xml文件, Spring提供以下Bean来注册三大组件
ServletRegistrationBean 注册自定义
Servlet FilterRegistrationBean 注册自定义
Filter ServletListenerRegistrationBean 注册自定义Listener
如果使用传统 @WebFilter...实现注册也可以
条件:
- 一定是自定义组件
- 启动类添加@ServletComponentScan
4.5 切换为其他嵌入式Servlet容器
SpringBoot 默认针对Servlet容器提供以下支持:
- Tomcat(默认使用)
- Jetty:支持长连接项目(如:聊天页面)
- Undertow:不支持JSP,但是并发性能高,是高性能非阻塞的容器
默认Tomcat容器
在spring-boot-starter-web启动器中默认引入了tomcat容器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>2.1.0.RELEASE</version>
<scope>compile</scope>
</dependency>
切换 Jetty 容器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- 排除tomcat容器 -->
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<!--引入其他的Servlet容器-->
<dependency>
<artifactId>spring-boot-starter-jetty</artifactId>
<groupId>org.springframework.boot</groupId>
</dependency>
使用外置Servlet容器Tomcat9.x
嵌入式Servlet容器:运行启动类就可启动,或将项目打成可执行的 jar 包
优点:简单、快捷;
缺点:默认不支持JSP、优化定制比较复杂使用定制器, 还需要知道 每个功能 的底层原理
外置Servlet容器:配置 Tomcat, 将项目部署到Tomcat中运行