Springmvc 简明教程
Spring - MVC Framework Overview
Spring Web MVC框架提供了一个模型-视图-控制器架构和可以用来开发灵活且松散耦合的web应用程序的准备组件。MVC模式导致应用程序的不同方面(输入逻辑、业务逻辑和界面逻辑)分离,同时在这些元素之间提供松散耦合。
The Spring Web MVC framework provides a model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements.
-
The Model encapsulates the application data and in general, they will consist of POJO.
-
The View is responsible for rendering the model data and in general, it generates HTML output that the client’s browser can interpret.
-
The Controller is responsible for processing User Requests and Building Appropriate Model and passes it to the view for rendering.
The DispatcherServlet
Spring Web模型-视图-控制器(MVC)框架是围绕一个DispatcherServlet设计的,它处理所有的HTTP请求和响应。Spring Web MVC DispatcherServlet的请求处理工作流显示在下图中。
The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that handles all the HTTP requests and responses. The request processing workflow of the Spring Web MVC DispatcherServlet is shown in the following illustration.
以下为响应发送到 DispatcherServlet 的入站 HTTP 请求的事件序列 -
Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet −
-
After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller.
-
The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet.
-
The DispatcherServlet will take help from ViewResolver to pick up the defined view for the request.
-
Once view is finalized, The DispatcherServlet passes the model data to the view, which is finally rendered, on the browsers.
所有以上提到的组件,比如HandlerMapping、Controller和ViewResolver都是 WebApplicationContext 的一部分,它扩展了平实的 ApplicationContext ,其中有一些web应用程序所必需的额外功能。
All the above-mentioned components, i.e. HandlerMapping, Controller and ViewResolver are parts of WebApplicationContext, which is an extension of the plain ApplicationContext with some extra features necessary for web applications.
Required Configuration
我们需要映射DispatcherServlet需要处理的请求,通过在 web.xml 文件中使用URL映射来实现。以下示例显示了 HelloWeb DispatcherServlet的声明和映射——
We need to map requests that you want the DispatcherServlet to handle, by using a URL mapping in the web.xml file. The following is an example to show declaration and mapping for 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>
web.xml 文件将被保留在你的web应用程序的 WebContent/WEB-INF 目录中。初始化DispatcherServlet时,框架将尝试从一个名为 [servlet-name]-servlet.xml 的文件中加载应用程序上下文,该文件位于应用程序的WebContent/WEB-INF目录中。在本例中,我们的文件将是 HelloWeb-servlet.xml 。
The web.xml file will be kept in the WebContent/WEB-INF directory of your web application. Upon initialization of the HelloWeb DispatcherServlet, the framework will try to load the application context from a file named [servlet-name]-servlet.xml located in the application’s WebContent/WEB-INF directory. In this case, our file will be HelloWeb-servlet.xml.
接下来, <servlet-mapping> 标签指出了哪些URL将由哪个DispatcherServlet处理。在这里,所有以.jsp结尾的HTTP请求都将由 HelloWeb DispatcherServlet处理。
Next, the <servlet-mapping> tag indicates which URLs will be handled by which DispatcherServlet. Here, all the HTTP requests ending with .jsp will be handled by the HelloWeb DispatcherServlet.
如果你不想使用默认的文件名 [servlet-name]-servlet.xml 和默认位置WebContent/WEB-INF,你可以通过在你的web.xml文件中添加 ContextLoaderListener servlet监听器,来自定义这个文件名和位置,如下所示——
If you do not want to go with the default filename as [servlet-name]-servlet.xml and default location as WebContent/WEB-INF, you can customize this file name and location by adding the servlet listener ContextLoaderListener in your web.xml file as follows −
<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>
现在,让我们查看放置在你的web应用程序的WebContent/WEB-INF目录中的 HelloWeb-servlet.xml 文件的所需配置。
Now, let us check the required configuration for HelloWeb-servlet.xml file, placed in your web application’s WebContent/WEB-INF directory.
<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>
以下是有关 HelloWeb-servlet.xml 文件的部分重点:
Following are some important points about HelloWeb-servlet.xml file −
-
The [servlet-name]-servlet.xml file will be used to create the beans defined, overriding the definitions of any beans defined with the same name in the global scope.
-
The <context:component-scan…> tag will be used to activate the Spring MVC annotation scanning capability, which allows to make use of annotations like @Controller and @RequestMapping, etc.
-
The InternalResourceViewResolver will have rules defined to resolve the view names. As per the above-defined rule, a logical view named hello is delegated to a view implementation located at /WEB-INF/jsp/hello.jsp.
现在让我们了解如何创建实际组件,即控制器、模型和视图。
Let us now understand how to create the actual components i.e., Controller, Model and View.
Defining a Controller
DispatcherServlet 将请求委托给 controller 以执行特定于该请求的功能。 @Controller 注解表明特定的类扮演 controller 的角色。 @RequestMapping 注解用于将 URL 映射到整个类或特定的处理方法。
The DispatcherServlet delegates the request to the controllers to execute the functionality specific to it. The @Controller annotation indicates that a particular class serves the role of a controller. The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.
@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 注解将类定义为 Spring MVC 控制器。在此,第一个 @RequestMapping 用法表示该控制器上的所有处理方法都与 /hello 路径相关。
The @Controller annotation defines the class as a Spring MVC controller. Here, the first usage of @RequestMapping indicates that all handling methods on this controller are relative to the /hello path.
下一个注解 @RequestMapping (method = RequestMethod.GET) 用于将 printHello() 方法声明为控制器的默认服务方法来处理 HTTP GET 请求。我们可以在同一 URL 上定义另一个方法来处理任何 POST 请求。
The next annotation @RequestMapping (method = RequestMethod.GET) is used to declare the printHello() method as the controller’s default service method to handle HTTP GET request. We can define another method to handle any POST request at the same URL.
我们还可以用另一种形式编写上述控制器,其中我们可以按照如下方式在 @RequestMapping 中添加其他属性:
We can also write the above controller in another form, where we can add additional attributes in the @RequestMapping as follows −
@Controller
public class HelloController{
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
value 属性指示处理程序方法映射到的 URL, method 属性定义了处理 HTTP GET 请求的服务方法。
The value attribute indicates the URL to which the handler method is mapped and the method attribute defines the service method to handle the HTTP GET request.
以下是有关上述控制器定义的部分重点:
Following are some important points to be noted regarding the controller defined above −
-
You will define the required business logic inside a service method. You can call another method inside this method as per the requirement.
-
Based on the business logic defined, you will create a model within this method. You can set different model attributes and these attributes will be accessed by the view to present the result. This example creates a model with its attribute "message".
-
A defined service method can return a String, which contains the name of the view to be used to render the model. This example returns "hello" as the logical view name.
Creating JSP Views
Spring MVC 支持许多不同展现技术的视图类型。这些包括 JSPs, HTML, PDF, Excel Worksheets, XML, Velocity Templates, XSLT, JSON, Atom 和 RSS 数据源、 JasperReports 等等。然而,最常见的是使用 JSTL 编写的 JSP 模板。所以,让我们在 /WEB-INF/hello/hello.jsp 中编写一个简单的问候视图:
Spring MVC supports many types of views for different presentation technologies. These include - JSPs, HTML, PDF, Excel Worksheets, XML, Velocity Templates, XSLT, JSON, Atom and RSS feeds, JasperReports, etc. However, the most common ones are the JSP templates written with JSTL. So, let us write a simple hello view in /WEB-INF/hello/hello.jsp −
<html>
<head>
<title>Hello Spring MVC</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
此处, ${message} 是我们在控制器中设置的属性。您可以在视图中显示多个属性。
Here ${message} Here is the attribute, which we have setup inside the Controller. You can have multiple attributes to be displayed inside your view.