[Bài đọc] Controller

1. Tổng quan

Spring controller nhận ủy quyền xử lý các request từ phía front controller. Công việc cơ bản của nó là nhận dữ liệu cần thiết từ front controller, xác định view cần sử dụng, triệu gọi lớp xử lý nghiệp vụ cần thiết, sắp xếp dữ liệu mà view cần đến vào model, gửi thông tin về view cùng model lại cho front controller.

Tới bản SpringMVC hiện tại, sau khi cho phép sử dụng annotion controller, một class được ấn định thành controller bằng cách sử dụng annotation @Controller.

Cấu hình dưới đây cho phép sử dụng annotation cho controller:

<mvc:annotation-driven />

Các annotation của controller cần được phát hiện để thực hiện phương thức xử lý. Khai báo trong tập cấu hình sau cung cấp thông tin cho framework biết về package nào cần quét để phát hiện các class controller:

<context:component-scan base-package="com.packt.*"></context:component-scan>

Ví dụ sau đây biểu diễn cấu trúc của một Controller:

@Controller
public class ProductController {

@Autowired
private ProductService productService;

@GetMapping("/products")
public ModelAndView listProducts() {
List<Product> products = productService.findAll();
ModelAndView modelAndView = new ModelAndView("/product/list");
modelAndView.addObject("products", products);
return modelAndView;
}

@GetMapping("/create-product")
public ModelAndView showCreateForm() {
ModelAndView modelAndView = new ModelAndView("/product/create");
modelAndView.addObject("product", new Product());
return modelAndView;
}

@PostMapping("/create-product")
public ModelAndView saveProduct(@ModelAttribute("product") Product product) {
productService.save(product);

ModelAndView modelAndView = new ModelAndView("/product/create");
modelAndView.addObject("product", new Product());
modelAndView.addObject("message", "New product created successfully");
return modelAndView;
}
}

Nhìn vào lớp ProductController chúng ta vừa tạo ở trên, có thể thấy một Controller trong Spring MVC có các thành phần cơ bản sau:

– Một annotation @Controller được khai báo cùng với định nghĩa của lớp ProductController

– Các annotation @GetMapping, @PostMapping được khai báo cùng với định nghĩa của các phương thức trong lớp ProductController

– Các phương thức listProducts(), showCreateForm(), saveProduct() của lớp ProductCOntroller, các phương thức này xử lý các Request để thực hiện các logic nghiệp vụ.

Chi tiết về Controller trong Spring MVC, chúng ta sẽ cùng nhau đi tìm hiểu trong các bài học sau.

Leave a Reply

Your email address will not be published.