Spring 简明教程

Spring - MVC Framework

Spring Web MVC 框架提供了模型-视图-控制器 (MVC) 架构和可用作开发灵活且松散耦合的 Web 应用程序的现成组件。MVC 模式导致应用程序的不同方面(输入逻辑、业务逻辑和 UI 逻辑)分离,同时在这些元素中提供松散耦合。

The Spring Web MVC framework provides Model-View-Controller (MVC) 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.

  1. The Model encapsulates the application data and in general they will consist of POJO.

  2. The View is responsible for rendering the model data and in general it generates HTML output that the client’s browser can interpret.

  3. The Controller is responsible for processing user requests and building an appropriate model and passes it to the view for rendering.

The DispatcherServlet

Spring Web 模型-视图-控制器(MVC)框架围绕着处理所有 HTTP 请求和响应的 DispatcherServlet 而设计。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 illustrated in the following diagram −

spring dispatcherservlet

以下为响应发送到 DispatcherServlet 的入站 HTTP 请求的事件序列 -

Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet −

  1. After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller.

  2. 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.

  3. The DispatcherServlet will take help from ViewResolver to pickup the defined view for the request.

  4. Once view is finalized, The DispatcherServlet passes the model data to the view which is finally rendered on the browser.

所有上述组件(即 HandlerMapping、Controller 和 ViewResolver)都是 WebApplicationContext 的一部分,WebApplicationContext 是带有额外功能的 plainApplicationContext 的扩展(这些功能对于 Web 应用程序而言非常有必要)。

All the above-mentioned components, i.e. HandlerMapping, Controller, and ViewResolver are parts of WebApplicationContext which is an extension of the plainApplicationContext with some extra features necessary for web applications.

Required Configuration

您需要使用 web.xml 文件中的 URL 映射来映射您希望 DispatcherServlet 处理的请求。以下示例展示了 HelloWeb DispatcherServlet 的声明和映射 -

You 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 example −

<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 目录中。在初始化 HelloWeb DispatcherServlet 时,框架将尝试从位于该应用程序的 WebContent/WEB-INF 目录中的名为 [servlet-name]-servlet.xml 的文件中加载应用程序上下文。在本案例中,我们的文件将是 HelloWebservlet.xml

The web.xml file will be kept in the WebContent/WEB-INF directory of your web application. Upon initialization of 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 HelloWebservlet.xml.

接下来,<servlet-mapping> 标记表明哪些 URL 将由哪个 DispatcherServlet 处理。这里,所有以 .jsp 结尾的 HTTP 请求都将由 HelloWeb DispatcherServlet 处理。

Next, <servlet-mapping> tag indicates what 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 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 the important points about HelloWeb-servlet.xml file −

  1. 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.

  2. The <context:component-scan…​> tag will be use to activate Spring MVC annotation scanning capability which allows to make use of annotations like @Controller and @RequestMapping etc.

  3. 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 .

以下部分将向您展示如何创建您的实际组件,即 Controller、Model 和 View。

The following section will show you how to create your 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 controller。这里,首次使用 @RequestMapping 表明此 controller 上的所有处理方法都相对于 /hello 路径。接下来,注解 @RequestMapping(method = RequestMethod.GET) 用于将 printHello() 方法声明为 controller 处理 HTTP GET 请求的默认服务方法。您可以在相同的 URL 定义另一个方法来处理任何 POST 请求。

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. 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. You can define another method to handle any POST request at the same URL.

您可以用另一种形式来编写上述 controller,其中可以在 @RequestMapping 中添加附加的属性,如下所示: -

You can write the above controller in another form where you can add additional attributes in @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 属性表示处理程序方法映射到的网址, 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 HTTP GET request. The following important points are to be noted about the controller defined above −

  1. You will define required business logic inside a service method. You can call another method inside this method as per requirement.

  2. Based on the business logic defined, you will create a model within this method. You can use setter different model attributes and these attributes will be accessed by the view to present the final result. This example creates a model with its attribute "message".

  3. 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 logical view name.

Creating JSP Views

Spring MVC 支持许多类型的视图以用于不同的表示技术。其中包括有:JSP、HTML、PDF、Excel 工作表、XML、Velocity 模板、XSLT、JSON、Atom 和 RSS 源、JasperReports 等。但是,我们最常使用带有 JSTL 的 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. But most commonly we use JSP templates written with JSTL.

让我们在 /WEB-INF/hello/hello.jsp 中编写一个简单的 hello 视图:

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} is the attribute which we have set up inside the Controller. You can have multiple attributes to be displayed inside your view.

Spring Web MVC Framework Examples

基于上述概念,让我们查看几个重要的示例,它们将帮助您构建您的 Spring Web 应用程序:

Based on the above concepts, let us check few important examples which will help you in building your Spring Web Applications −

Sr.No.

Example & Description

1

Spring MVC Hello World ExampleThis example will explain how to write a simple Spring Web Hello World application.

2

Spring MVC Form Handling ExampleThis example will explain how to write a Spring Web application using HTML forms to submit the data to the controller and display a processed result.

3

Spring Page Redirection ExampleLearn how to use page redirection functionality in Spring MVC Framework.

4

Spring Static Pages ExampleLearn how to access static pages along with dynamic pages in Spring MVC Framework.

5

Spring Exception Handling ExampleLearn how to handle exceptions in Spring MVC Framework.