java 項目 , controller.java , service.java ???
时间: 2023-11-30 22:43:26 浏览: 77
knockout-2.2.0.debug,java项目开发源码,javaoajbpm项目
您好!Java项目通常采用MVC架构,其中Controller层负责接收请求并调用Service层处理业务逻辑,最后将处理结果返回给前端。Service层则负责具体的业务逻辑处理,例如数据的增删改查等操作。下面是一个简单的Java项目Controller层和Service层的示例:
Controller.java:
```java
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public List<User> getAllUsers() {
return userService.getAllUsers();
}
@GetMapping("/users/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
@PostMapping("/users")
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}
@PutMapping("/users/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
return userService.updateUser(id, user);
}
@DeleteMapping("/users/{id}")
public void deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
}
}
```
Service.java:
```java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> getAllUsers() {
return userRepository.findAll();
}
public User getUserById(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User", "id", id));
}
public User createUser(User user) {
return userRepository.save(user);
}
public User updateUser(Long id, User userDetails) {
User user = userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User", "id", id));
user.setName(userDetails.getName());
user.setEmail(userDetails.getEmail());
return userRepository.save(user);
}
public void deleteUser(Long id) {
User user = userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User", "id", id));
userRepository.delete(user);
}
}
```
阅读全文