Spring Boot Web 开发基础
概述
Spring Boot 提供了一种快速构建 Web 应用的方式,开发者只需选择所需的模块并编写业务逻辑即可。
自动配置机制
Spring Boot 的核心之一是自动配置功能。例如:
xxxAutoConfiguration:为容器提供自动配置的组件。xxxProperties:封装配置文件的内容。
静态资源映射规则
以下是 Spring Boot 中静态资源的映射规则:
@Configuration
public class StaticResourceConfig {
@Bean
public ResourceHandlerRegistrationCustomizer resourceHandlerCustomizer() {
return registration -> registration.setCachePeriod(3600);
}
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ResourceProperties resourceProps) {
return new WelcomePageHandlerMapping(resourceProps.getWelcomePage(), "/**");
}
}
1. 所有以 /webjars/** 开头的请求会从 classpath:/META-INF/resources/webjars/ 路径中查找资源。
2. 以 /** 匹配的请求会在以下路径中查找:
classpath:/META-INF/resources/classpath:/resources/classpath:/static/classpath:/public/
3. 欢迎页面(如 index.html)会被映射到根路径。
4. 图标文件(favicon.ico)会在静态资源目录下查找。
JSON 接口开发
通过使用 @RestController 注解,方法默认返回 JSON 格式数据:
@RestController
public class UserController {
@GetMapping("/user")
public User getUser() {
User user = new User();
user.setName("张三");
user.setEmail("zhangsan@example.com");
return user;
}
}
自定义过滤器
可以通过实现 Filter 接口来自定义过滤器:
@Component
public class LoggingFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
System.out.println("访问 URL: " + httpRequest.getRequestURI());
chain.doFilter(request, response);
}
}
自定义属性
在 application.properties 文件中添加配置项,并通过自定义类读取:
@Component
@ConfigurationProperties(prefix = "custom.config")
public class CustomConfig {
private String title;
private String description;
// Getter 和 Setter 方法
}
日志配置
日志级别和输出路径可以在配置文件中指定:
logging.file.path=/var/log/myapp
logging.level.root=INFO
logging.level.org.springframework.web=DEBUG
数据库操作
使用 JPA 进行数据库操作:
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private BigDecimal price;
// Getter 和 Setter 方法
}
public interface ProductRepository extends JpaRepository {
List<Product> findByName(String name);
}
Thymeleaf 模板引擎
Thymeleaf 是一种现代模板引擎,支持直接在浏览器中预览模板:
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="${message}">默认文本</p>
</body>
</html>
引入 Thymeleaf 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>