Spring Web 搭建与配置指南
环境准备
确保已安装 JDK 8 或更高版本,推荐使用 Maven 或 Gradle 作为构建工具。IDE 可选择 IntelliJ IDEA 或 Eclipse。
创建项目
通过 Spring Initializr 生成项目模板,勾选 "Spring Web" 依赖。或手动在 Maven 的 pom.xml 中添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
项目结构
标准结构应包含:
src/main/java:主代码目录src/main/resources:配置文件目录src/test:测试代码目录
配置应用入口
创建主启动类,通常放在根包下:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
基础控制器示例
创建简单的 REST 控制器:
@RestController
@RequestMapping("/api")
public class DemoController {
@GetMapping("/hello")
public String sayHello() {
return "Hello Spring Web";
}
}
配置文件
在 application.properties 或 application.yml 中配置基本参数:
server.port=8080
server.servlet.context-path=/demo
静态资源处理
默认静态资源路径为:
/static/public/resources/META-INF/resources
自定义拦截器
实现 HandlerInterceptor 接口并注册:
public class CustomInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
// 预处理逻辑
return true;
}
}
注册拦截器:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CustomInterceptor());
}
}
异常处理
使用 @ControllerAdvice 全局异常处理:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception e) {
return ResponseEntity.status(500).body(e.getMessage());
}
}
测试验证
创建测试类验证控制器:
@SpringBootTest
@AutoConfigureMockMvc
class DemoControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testHello() throws Exception {
mockMvc.perform(get("/api/hello"))
.andExpect(status().isOk())
.andExpect(content().string("Hello Spring Web"));
}
}
部署运行
通过命令启动应用:
mvn spring-boot:run
或打包为可执行 JAR:
mvn clean package
java -jar target/your-app.jar
性能优化建议
- 启用 GZIP 压缩:
server.compression.enabled=true - 配置连接池参数
- 启用 HTTP/2(需 SSL 支持)
- 合理设置 Tomcat 线程池参数
安全配置
添加 Spring Security 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
基础安全配置示例:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin();
}
}

1174

被折叠的 条评论
为什么被折叠?



