springmvc编写 部门增删改查 请求 POST http://localhost:8080/depts Body: { "name":"人事部", "user":"负责人张三" } 响应 success
时间: 2024-09-25 15:09:11 浏览: 41
在Spring MVC中编写部门(dept)的增删改查操作,通常会涉及以下几个步骤:
1. **创建实体类(Department)**:
```java
public class Department {
private String name;
private String responsiblePerson;
// getters and setters
}
```
2. **数据访问层(DAO)**:
```java
public interface DepartmentDAO {
void create(Department department);
void update(Department department);
void delete(String id);
Department findById(String id);
}
```
3. **服务层(Service)**:
```java
@Service
public class DepartmentService {
@Autowired
private DepartmentDAO dao;
public void addDepartment(Department dept) {
dao.create(dept);
}
public void updateDepartment(Department dept) {
dao.update(dept);
}
public void deleteDepartment(String id) {
dao.delete(id);
}
public Department getDepartmentById(String id) {
return dao.findById(id);
}
}
```
4. **控制器层(Controller)**:
```java
@RestController
@RequestMapping("/depts")
public class DepartmentController {
@Autowired
private DepartmentService service;
@PostMapping
public ResponseEntity<?> create(@RequestBody Department dept) {
try {
service.addDepartment(dept);
return new ResponseEntity<>("success", HttpStatus.CREATED);
} catch (Exception e) {
return new ResponseEntity<>("error", HttpStatus.BAD_REQUEST);
}
}
// ...其他HTTP方法对应 delete、update 和 get
}
```
5. **处理成功和错误情况**:
- 当请求成功时,返回`"success"`和HTTP状态码`201 Created`(创建资源)
- 如果出现异常,返回适当的错误信息和状态码(如`400 Bad Request`)
使用上述设计,当发送POST请求到`http://localhost:8080/depts`并携带JSON内容`{ "name": "人事部", "user": "负责人张三" }`时,Spring MVC将调用对应的`create`方法添加新的部门。
阅读全文