Làm sao để phân biệt update, add, delete khi gửi action từ client trong Spring

Làm sao để phân biệt update, add, delete khi gửi action từ client trong Spring

Bên trong mỗi controller sẽ chứa các phương thức, các phương thức sẽ đảm nhiệm việc nhận yêu cầu từ các URL. Để biết phương thức nào sẽ nhận yêu cầu từ URL nào, ta đặt annotation @RequestMapping với tham số là url tương ứng bên trên phương thức mỗi phương thức.


- Tham số trong mỗi phương thức trên có thể biến đổi tùy vào việc ta muốn lấy gì từ yêu cầu gửi lên server. Tham số có thể là một đối tượng của HttpRequest, HttpResponse, hoặc một đối tượng của model A nào đó. Trong đối tượng của lớp A, sẽ lưu các thông tin được gửi lên từ View (*.jsp), phương thức trong controller sẽ tiếp nhận các thông tin này và xử lý chúng.

- Mỗi một phương thức trong controller sẽ trả về một đối tượng của lớp ModelAndView. Lớp này là đại diện cho một view, là nơi mà sẽ được ứng dụng chuyển tiếp đến sau khi controller xử lý xong nghiệp vụ.
ví dụ ta có controller sau:

 @Controller  
 public class DemoController{  

      @RequestMapping(value="/home", method=RequestMethod.GET)  
      public ModelAndView handleRequest(HttpServletRequest request,  
                HttpServletResponse response) throws Exception {  

           Student student = new Student();  
           student.setName("Coder Tien Sinh");  

           List<String> books = new ArrayList<String>();  
           books.add("book1");  
           books.add("book2");  
           student.setBooks(books);  

           ModelAndView mav = new ModelAndView("index.jsp", "model", student);  
           return mav;  
      }  

      @RequestMapping(value="/submitStudentInfo", method = RequestMethod.POST)  
      public ModelAndView submitStudentInfo(ModelMap model, @ModelAttribute("model") Student student){  

           List<String> listBooks = student.getBooks();  
           
           String message = "Update success !!!";  
           if(listBooks.size()>0 ){  
                message = "Have Books in listBook !!!";  
           }  
           model.addAttribute("message", message);  

           ModelAndView mav = new ModelAndView("index.jsp", "model", student);  
           return mav;  
      }     
 }

Trong ví dụ của chúng ta, ta có hai đường dẫn, “/home“, và “/submitStudentInfo“. Các yêu cầu được gửi từ “/home” sẽ được phương thức handleRequest() trong controller xử lý, và tương tự các yêu cầu được gửi từ “/submitStudentInfo” sẽ được phương thức submitStudentInfo() trong controller xử lý. Tuy nhiên không phải yêu cầu nào từ “/home” cũng sẽ được phương thức handleRequest() xử lý, ở đây chỉ nhưng yêu cầu có kiểu GET mới được chuyển tiếp đến handleRequest(), ngược lại chỉ những yêu cấu có kiểu POST mới được chuyển tiếp đến phương thức submitStudentInfo(). Điều này được thực hiện qua việc chỉ ra RequestMethod trong annotation RequestMapping

No comments:

Post a Comment