Spring MVC cung cấp kiến trúc model-view-controller và các thành phần để có thể được sử dụng phát triển các ứng dụng web. Mô hình MVC phân tách các khía cạnh khác nhau của ứng dụng (logic đầu vào, logic business, và giao diện người dùng logic), và cung cấp một kết nối giữa các yếu tố này.
MVC framework được thiết kế xoay quanh DispatcherServlet - cho phép xử lý tất cả các HTTP request và resoinse. Sơ đồ dưới đây giải thích flow xử lý request của Spring Web MVC DispatcherServlet.
Đây là chuỗi các sự kiện tương ứng với một yêu cầu HTTP đến DispatcherServlet:
Tất cả các thành phần nêu trên, ví dụ như. HandlerMapping, Controller và ViewResolver là bộ phận của WebApplicationContext - một mở rộng của ApplicationContext với một số tính năng bổ sung cần thiết cho các ứng dụng web.
Bạn cần một sơ đồ request mà bạn muốn DispatcherServlet xử lý, bằng cách sử dụng một ánh xạ URL trong file web.xml. Sau đây là một ví dụ thể hiện cho việc triển khai, lập bản đồ cho HelloWeb DispatcherServlet:
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
</web-app>
Các tập tin web.xml sẽ được lưu trong thư mục WebContent/WEB-INF trong application của bạn. Khi khởi tạo HelloWeb DispatcherServlet, framework sẽ load nội dung từ file [servlet-name]-servlet.xml đặt trong WebContent/WEB-INF. Trong trường hợp này thì file sẽ là HelloWeb-servlet.xml.
Tiếp theo, <servlet-mapping>
cho thấy những URL sẽ được xử lý trong DispatcherServlet. Ở đây tất cả các request HTTP kết thúc với .jsp sẽ được xử lý bởi HelloWeb DispatcherServlet.
Nếu bạn ko muốn dùng default filename kiểu [servlet-name]-servlet.xml và vị trí là WebContent/WEB-INF, bạn có thể customize file name và đường dẫn bằng cách cho thêm servlet listener ContextLoaderListener trong web.xml như dưới đây :
<web-app...>
<!-------- DispatcherServlet definition goes here----->
....
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/HelloWeb-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
Hãy kiểm tra phần cấu hình cần thiết cho file HelloWeb-servlet.xml đặt trong WebContent/WEB-INF :
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.tutorialspoint" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Sau đây là những điểm quan trọng về file HelloWeb-servlet.xml:
Phần kế tiếp sẽ hướng dẫn bạn tạo các components như Controller, Model, View.
DispatcherServlet sẽ chuyển một request đến controllers để xử lý những chức năng được yêu cầu trong đó. annotation @Controller cho thấy rằng một class đặct biệt phục vụ một vai trò của một Controller. @RequestMapping được sử dụng để map một URL đến toàn bộ class or một method trong class đó.
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
@Controller định nghĩa một class như một controller Spring MVC. Ở đây, @RequestMapping cho thây tất cả các motheds trong controller này liên quan đến path /hello. @RequestMapping(method = RequestMethod.GET) được sử dụng để khải báo printHello() như là method service default của controller để xử lý HTTP GET request. Bạn có thể định nghia method khác để xử lý POST trên cùng một URL.
Bạn có thể viết controller ở trên trong form khác nơi bạn có thể cho thêm một vài thuộc tính bổ sung trong @RequestMapping như dưới đây :
@Controller
public class HelloController{
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
Thuộc tính giá trị cho thấy URL mà theo đó các method sẽ được map tương ứng và thuộc tính method định nghĩa service method để xử lý request POST GET. Có một vài điểm quan trọng cần chú ý về controller được định nghĩa ở trên :
Bạn sẽ định nghĩa logic business cần thiết trong một service method. Bạn có thể call một method khác bên trong method này. Dựa trên logic business được định nghĩa, bạn có thể tạo nên một Model trong method này. Bạn có thể tạo thêm các thuộc tính model và các thuộc tính này có thể được access từ View để hiển thị kết quả cuối cùng. Đây là ví dụ tạo một Model với thuộc tính "message". Method server có thể trả lại một String - chưa tên của View để sử dụng cho việc render Model. Đây là ví dụ trả lại view tên là "hello" .
Spring MVC hỗ trợ nhiều kỹ thuật hiển thị khác nhau. JSPs, HTML, PDF, Excel worksheets, XML, Velocity templates, XSLT, JSON, Atom và RSS feeds, JasperReports v.v... Nhưng phổ biến nhất là sử dụng JSP được viết với JSTL. Ở đây chúng ta sẽ viết một View hello đơn giản trong /WEB-INF/hello/hello.jsp :
<html>
<head>
<title>Hello Spring MVC</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
${message} là một thuộc tính được setup trong Controller. Bạn có thể thực hiện hiển thị nhiều thuộc tính trong phía View.
Unpublished comment
Viết câu trả lời