请给我部门管理系统增删查询的controller层示例代码
时间: 2024-09-25 09:02:53 浏览: 29
jsp+serlvet增删改查员工系统
在Java的Spring MVC框架下,一个简单的部门管理系统Controller层(通常是DepartmentController)的增删查改操作可能会像下面这样:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/departments")
public class DepartmentController {
private final DepartmentService departmentService; // 假设departmentService是一个依赖注入的服务
@Autowired
public DepartmentController(DepartmentService departmentService) {
this.departmentService = departmentService;
}
// 创建部门
@PostMapping
public ResponseEntity<Department> createDepartment(@RequestBody Department department) {
if (departmentService.create(department)) {
return new ResponseEntity<>(department, HttpStatus.CREATED);
} else {
return new ResponseEntity<>("Failed to create department", HttpStatus.BAD_REQUEST);
}
}
// 删除部门
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteDepartment(@PathVariable Long id) {
if (departmentService.delete(id)) {
return ResponseEntity.noContent().build();
} else {
return new ResponseEntity<>("Failed to delete department", HttpStatus.NOT_FOUND);
}
}
// 查询所有部门
@GetMapping
public List<Department> getAllDepartments() {
return departmentService.getAllDepartments();
}
// 根据ID查询单个部门
@GetMapping("/{id}")
public ResponseEntity<Department> getDepartmentById(@PathVariable Long id) {
Department department = departmentService.getDepartmentById(id);
if (department != null) {
return new ResponseEntity<>(department, HttpStatus.OK);
} else {
return new ResponseEntity<>("Department not found", HttpStatus.NOT_FOUND);
}
}
// 更新部门信息
@PutMapping("/{id}")
public ResponseEntity<Void> updateDepartment(@PathVariable Long id, @RequestBody Department updatedDepartment) {
if (departmentService.update(id, updatedDepartment)) {
return ResponseEntity.ok().build();
} else {
return new ResponseEntity<>("Failed to update department", HttpStatus.BAD_REQUEST);
}
}
阅读全文