4.10 本章习题
1)使用IDEA手动创建一个Spring Boot项目,创建一个控制器(Controller),模拟数据的增、删、改、查操作。
package com.example.demo.controller;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/users")
public class UserController {
private Map<Integer,String> userDatabase = new HashMap<>();
public UserController() {
userDatabase.put(1,"Alice");
userDatabase.put(2,"Bob");
}
@GetMapping
public List<Map.Entry<Integer,String>> getAllUsers() {
return new ArrayList<>(userDatabase.entrySet());
}
@GetMapping("/{id}")
public String user(@PathVariable Integer id) {
return userDatabase.get(id);
}
@PostMapping
public String addUser(@RequestParam Integer id, @RequestParam String name) {
userDatabase.put(id,name);
return "User added successfully";
}
@PutMapping("/{id}")
public String updateUser(@PathVariable Integer id, @RequestParam String name) {
if(userDatabase.containsKey(id)) {
userDatabase.put(id,name);
return "User updated successfully";
}
return "User not found";
}
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable Integer id) {
if(userDatabase.containsKey(id)) {
userDatabase.remove(id);
return "User deleted successfully";
}
return "User not found";
}
}
Postman测试结果:
新增
- 使用拦截器实现全局系统性能监控日志。
步骤 1:创建一个性能监控拦截器PerformanceInterceptor
package com.example.demo.interceptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component
public class PerformanceInterceptor implements HandlerInterceptor {
private static final String START_TIME = "startTime";
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
request.setAttribute(START_TIME, System.currentTimeMillis());
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
long startTime = (Long) request.getAttribute(START_TIME);
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
String logMessage = String.format("Request to %s took %d ms", request.getRequestURI(), duration);
System.out.println(logMessage);
}
}
步骤 2:配置拦截器 创建一个 WebConfig 类,并注册 PerformanceInterceptor
package com.example.demo.config;
import com.example.demo.interceptor.PerformanceInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private PerformanceInterceptor performanceInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(performanceInterceptor);
}
}
步骤 3:测试性能监控日志
- 使用WebMvcConfigurer自定义配置系统的静态文件路径。
步骤 1:创建 Web 配置类
package com.example.demo.config;
import com.example.demo.interceptor.PerformanceInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/custom-static/");
}
}
步骤 2:创建自定义的静态资源文件夹
在项目的 src/main/resources 目录下,创建一个 custom-static 文件夹,并在其中放置静态资源文件(如图片、CSS 文件、JavaScript 文件等)。
步骤 3:访问静态资源
启动 Spring Boot 应用后,访问以下 URL 以验证静态资源是否可用
图片文件: http://localhost:8080/static/images/logo.png
这些资源将被映射到 src/main/resources/custom-static 文件夹中的文件。通过这种方式,你可以轻松自定义和管理 Spring Boot 应用中的静态资源路径。