一、Web开发开发概览
使用 Spring Boot 进行 Web 开发,几乎不需要繁琐的 XML 配置,核心流程如下:
-
创建 Spring Boot 应用,勾选所需模块(如 Web、Thymeleaf 等);
-
Spring Boot 已为常见场景做好自动配置 ,只需在
application.properties中指定少量参数即可; -
你只需专注编写业务代码。
自动配置原理
每个场景 Spring Boot 都帮我们配置了什么?能不能修改?能修改哪些?能不能扩展?
带着这些问题,我们逐步展开。
二、静态资源映射规则
pring Boot 对静态资源有一套默认的映射规则,无需额外配置即可使用。
2.1webjars 映射
所有 /webjars/** 的请求,都会去 classpath:/META-INF/resources/webjars/ 下找资源。
WebJars 是以 Jar 包方式引入前端库(如 jQuery、Bootstrap)的方案,官网:WebJars - Web Libraries in Jars
示例:引入 jQuery
XML
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
访问路径:localhost:8080/webjars/jquery/3.3.1/jquery.js
2.2静态资源文件夹映射
/** 路径会去以下目录找资源(按优先级):
-
classpath:/META-INF/resources/ -
classpath:/resources/ -
classpath:/static/ -
classpath:/public/
所以访问 localhost:8080/abc 会去这些文件夹找 abc 文件。
三、模板引擎 Thymeleaf
Spring Boot 推荐使用 Thymeleaf 作为模板引擎,语法简洁,功能强大。
3.1引入依赖
XML
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3.2自动配置规则
从 ThymeleafProperties 可以看到默认配置:
XML
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
-
模板放在
src/main/resources/templates/下 -
后缀为
.html,可通过配置文件修改
3.3 快速上手
Controller:
java
@Controller
public class HelloController {
@RequestMapping("/success")
public String hello(Model model) {
model.addAttribute("hello", "<h1>zhangsan</h1>");
return "success";
}
}
模板 success.html(引入命名空间):
html
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<div th:text="${hello}"></div>
</body>
</html>
3.4 Thymeleaf 常用语法
标准表达式
| 类型 | 语法 |
|---|---|
| 变量表达式 | ${...} |
| 选择表达式 | *{...}(配合 th:object) |
| 国际化表达式 | #{...} |
| URL 表达式 | @{...} |
内置运算符
-
算术:
+ - * / % -
比较:
> < >= <=(也可用gt lt ge le) -
布尔:
and or not -
条件:
? :和?:(默认值)
常用标签
| 标签 | 作用 |
|---|---|
th:text |
替换文本 |
th:utext |
替换 HTML |
th:value |
属性赋值 |
th:if / th:unless |
条件判断 |
th:each |
循环 |
th:switch / th:case |
多路选择 |
th:href / th:src |
链接/资源 |
th:object / *{...} |
对象绑定 |
th:fragment / th:replace |
布局复用 |
四、Spring Boot 整合 Spring MVC
Spring Boot 自动配置了 Spring MVC 的核心组件,我们只需按需调整。
4.1自动管理的组件
| 组件 | 说明 |
|---|---|
DispatcherServlet |
自动注册,无需 web.xml |
Controller |
包扫描自动管理 |
ViewResolver |
ContentNegotiatingViewResolver 组合视图解析器 |
| 静态资源 | 按前述规则映射 |
| 消息转换器 | 默认支持 JSON 等 |
| 格式化器 | 如日期格式自动转换 |
4.2 文件上传配置
Spring Boot 自动配置了 MultipartResolver,只需在 Controller 中接收 MultipartFile。
上传大小限制可在配置文件中修改:
XML
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
4.3扩展 Spring MVC(实现 WebMvcConfigurer)
通过实现 WebMvcConfigurer 接口,我们可以保留自动配置的同时进行扩展。
添加视图控制器(请求转发)
java
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/tx").setViewName("success");
}
}
注册自定义格式化器
java
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addFormatter(new Formatter<Date>() {
@Override
public Date parse(String s, Locale locale) throws ParseException {
return new SimpleDateFormat("yyyy-MM-dd").parse(s);
}
@Override
public String print(Date date, Locale locale) {
return null;
}
});
}
替换消息转换器为 FastJson
引入依赖后,配置:
java
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter fc = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(SerializerFeature.PrettyFormat);
fc.setFastJsonConfig(config);
converters.add(fc);
}
注册拦截器
java
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/hello2");
}
五、嵌入式 Servlet 容器配置
Spring Boot 默认使用嵌入式 Tomcat,配置非常方便。
5.1修改容器配置
直接在 application.properties 中修改:
TypeScript
server.port=8081
server.servlet.context-path=/tx
server.tomcat.uri-encoding=UTF-8
5.2 注册 Servlet / Filter / Listener
由于没有 web.xml,通过 ServletRegistrationBean 等方式注册三大组件。
Servlet
java
@Bean
public ServletRegistrationBean myServlet() {
return new ServletRegistrationBean(new MyServlet(), "/myServlet");
}
Filter
java
@Bean
public FilterRegistrationBean myFilter() {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new MyFilter());
bean.setUrlPatterns(Arrays.asList("/hello", "/myServlet"));
return bean;
}
Listener
java
@Bean
public ServletListenerRegistrationBean myListener() {
return new ServletListenerRegistrationBean<>(new MyListener());
}
六、使用外置 Servlet 容器(部署为 WAR)
有时我们需要部署到外部 Tomcat,而不是打 Jar 包运行。
步骤
1.创建 WAR 项目(IDEA 中选 War 类型)
2.将内置 Tomcat 设为 provided
XML
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
3.编写启动类继承 SpringBootServletInitializer
java
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(YourMainApplication.class);
}
}
4.打包成 WAR,部署到外部 Tomcat