本文目录导读:

我来为你详细介绍Java控制器的开发案例,涵盖Spring MVC和Spring Boot两种主流方式。
基础Spring MVC控制器
1 简单控制器案例
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/user")
public class UserController {
// 返回视图
@GetMapping("/login")
public String login() {
return "login"; // 返回视图名称
}
// 返回数据
@GetMapping("/getInfo")
@ResponseBody
public String getUserInfo() {
return "用户信息";
}
// 返回带数据的视图
@GetMapping("/profile")
public ModelAndView profile() {
ModelAndView mv = new ModelAndView("profile");
mv.addObject("username", "张三");
mv.addObject("age", 25);
return mv;
}
}
2 RESTful风格控制器
package com.example.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/users")
public class UserRestController {
private Map<Integer, User> userMap = new HashMap<>();
// 查询所有用户
@GetMapping
public ResponseEntity<Map<Integer, User>> getAllUsers() {
return ResponseEntity.ok(userMap);
}
// 根据ID查询用户
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Integer id) {
User user = userMap.get(id);
if (user == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(user);
}
// 创建用户
@PostMapping
public ResponseEntity<String> createUser(@RequestBody User user) {
userMap.put(user.getId(), user);
return ResponseEntity.status(HttpStatus.CREATED)
.body("用户创建成功");
}
// 更新用户
@PutMapping("/{id}")
public ResponseEntity<String> updateUser(@PathVariable Integer id,
@RequestBody User user) {
if (!userMap.containsKey(id)) {
return ResponseEntity.notFound().build();
}
userMap.put(id, user);
return ResponseEntity.ok("用户更新成功");
}
// 删除用户
@DeleteMapping("/{id}")
public ResponseEntity<String> deleteUser(@PathVariable Integer id) {
if (userMap.remove(id) == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok("用户删除成功");
}
// 查询参数处理
@GetMapping("/search")
public ResponseEntity<List<User>> searchUsers(
@RequestParam(required = false) String name,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
List<User> result = new ArrayList<>();
for (User user : userMap.values()) {
if (name == null || user.getName().contains(name)) {
result.add(user);
}
}
return ResponseEntity.ok(result);
}
}
// 用户实体类
class User {
private Integer id;
private String name;
private Integer age;
private String email;
// getter和setter方法
// ...
}
Spring Boot控制器进阶
1 统一响应格式
package com.example.common;
// 统一响应类
public class ApiResponse<T> {
private int code;
private String message;
private T data;
private long timestamp;
public ApiResponse(int code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
this.timestamp = System.currentTimeMillis();
}
// 成功响应
public static <T> ApiResponse<T> success(T data) {
return new ApiResponse<>(200, "success", data);
}
// 失败响应
public static <T> ApiResponse<T> error(String message) {
return new ApiResponse<>(500, message, null);
}
// getter和setter
// ...
}
// 使用统一响应的控制器
@RestController
@RequestMapping("/api/products")
public class ProductController {
@GetMapping
public ApiResponse<List<Product>> getAllProducts() {
List<Product> products = productService.findAll();
return ApiResponse.success(products);
}
@GetMapping("/{id}")
public ApiResponse<Product> getProduct(@PathVariable Long id) {
return productService.findById(id)
.map(ApiResponse::success)
.orElse(ApiResponse.error("商品不存在"));
}
}
2 参数校验和异常处理
package com.example.controller;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
@RestController
@RequestMapping("/api/orders")
public class OrderController {
@PostMapping
public ApiResponse<Order> createOrder(@Valid @RequestBody OrderRequest request) {
// 参数校验由@Valid触发
Order order = orderService.create(request);
return ApiResponse.success(order);
}
@GetMapping("/{id}")
public ApiResponse<Order> getOrder(@PathVariable @Min(1) Long id) {
return orderService.findById(id)
.map(ApiResponse::success)
.orElseThrow(() -> new OrderNotFoundException(id));
}
}
// 请求体类
class OrderRequest {
@NotBlank(message = "订单名称不能为空")
private String name;
@Min(value = 0, message = "金额不能为负")
private double amount;
// getter和setter
}
// 全局异常处理
@RestControllerAdvice
public class GlobalExceptionHandler {
// 处理参数校验异常
@ExceptionHandler(MethodArgumentNotValidException.class)
public ApiResponse<?> handleValidationException(MethodArgumentNotValidException e) {
String message = e.getBindingResult().getAllErrors().stream()
.map(ObjectError::getDefaultMessage)
.collect(Collectors.joining(", "));
return ApiResponse.error(message);
}
// 处理自定义异常
@ExceptionHandler(OrderNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ApiResponse<?> handleOrderNotFound(OrderNotFoundException e) {
return ApiResponse.error(e.getMessage());
}
// 处理通用异常
@ExceptionHandler(Exception.class)
public ApiResponse<?> handleException(Exception e) {
return ApiResponse.error("系统异常:" + e.getMessage());
}
}
3 文件上传控制器
package com.example.controller;
import org.springframework.web.multipart.MultipartFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
@RestController
@RequestMapping("/api/file")
public class FileUploadController {
private final String uploadDir = "uploads/";
@PostMapping("/upload")
public ApiResponse<String> uploadFile(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return ApiResponse.error("文件不能为空");
}
try {
// 生成唯一文件名
String originalFilename = file.getOriginalFilename();
String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
String newFilename = UUID.randomUUID().toString() + extension;
// 保存文件
Path uploadPath = Paths.get(uploadDir + newFilename);
Files.createDirectories(uploadPath.getParent());
Files.write(uploadPath, file.getBytes());
return ApiResponse.success("文件上传成功:" + newFilename);
} catch (IOException e) {
return ApiResponse.error("文件上传失败:" + e.getMessage());
}
}
@PostMapping("/upload/multiple")
public ApiResponse<List<String>> uploadMultipleFiles(
@RequestParam("files") List<MultipartFile> files) {
List<String> filenames = new ArrayList<>();
for (MultipartFile file : files) {
if (!file.isEmpty()) {
try {
String filename = saveFile(file);
filenames.add(filename);
} catch (IOException e) {
return ApiResponse.error("部分文件上传失败");
}
}
}
return ApiResponse.success(filenames);
}
private String saveFile(MultipartFile file) throws IOException {
String originalFilename = file.getOriginalFilename();
String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
String newFilename = UUID.randomUUID().toString() + extension;
Path uploadPath = Paths.get(uploadDir + newFilename);
Files.createDirectories(uploadPath.getParent());
Files.write(uploadPath, file.getBytes());
return newFilename;
}
}
实用技巧和最佳实践
1 路径映射配置
@RestController
@RequestMapping("/api/v1") // API版本控制
public class AdvancedController {
// 路径变量
@GetMapping("/users/{userId}/orders/{orderId}")
public Order getUserOrder(
@PathVariable("userId") Long userId,
@PathVariable("orderId") Long orderId) {
return orderService.getUserOrder(userId, orderId);
}
// 通配符和正则
@GetMapping("/files/{filename:.+}")
public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
// 处理文件下载
}
}
2 请求拦截器
package com.example.config;
@Component
public class LoggingInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
System.out.println("请求URL: " + request.getRequestURL());
System.out.println("请求方法: " + request.getMethod());
System.out.println("开始时间: " + System.currentTimeMillis());
return true; // 返回true继续执行,false中断请求
}
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("请求处理完成");
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex) throws Exception {
System.out.println("请求结束");
}
}
// 注册拦截器
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private LoggingInterceptor loggingInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loggingInterceptor)
.addPathPatterns("/api/**")
.excludePathPatterns("/api/public/**");
}
}
3 跨域配置
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://localhost:3000") // 前端域名
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}
控制器测试
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testGetUser() throws Exception {
mockMvc.perform(get("/api/users/1")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("张三"));
}
@Test
public void testCreateUser() throws Exception {
String userJson = "{\"name\":\"李四\",\"age\":25}";
mockMvc.perform(post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content(userJson))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.code").value(200));
}
}
这些案例涵盖了Java控制器开发的主要场景和最佳实践,建议根据实际项目需求选择合适的实现方式,注意代码的规范性和可维护性。