从 Spring MVC 到 Spring Boot MVC

x33g5p2x  于2022-10-05 转载在 Spring  
字(10.0k)|赞(0)|评价(0)|浏览(699)

在本教程中,我们将了解 Spring Boot 如何通过使用其自动配置功能大大简化 Web 应用程序的创建,与旧的 Spring 方法进行比较。

Spring 框架用作开发 Web 应用程序的基础,MVC(模型视图控制器) 模式极大地简化了应用程序开发。让我们看看如何从一个简单的 Maven 原型开始构建一个标准的 Spring MVC 应用程序:

  1. $ mvn archetype:create -DgroupId=com.example -DartifactId=simple-mvc-app -DarchetypeArtifactId=maven-archetype-webapp

在对 pom.xml 文件进行一些调整后,我们将拥有这个项目文件:

  1. <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>simple-mvc-app</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <!-- Generic properties --> <java.version>1.8</java.version> <!-- Web --> <jsp.version>2.2</jsp.version> <jstl.version>1.2</jstl.version> <servlet.version>2.5</servlet.version> <!-- Spring --> <spring-framework.version>3.2.3.RELEASE</spring-framework.version> </properties> <dependencies> <!-- Spring MVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring-framework.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>${servlet.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>${jsp.version}</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>simple-mvc-app</finalName> </build> </project>

如您所见,我们使用的是 Spring MVC 版本 3.2.3.RELEASE 和一些其他依赖项,例如标签库。现在 Spring MVC 是 5.x 版本。接下来,我们看一下web.xml:

  1. <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>simple-web-spring-app</display-name> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/mvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>

如您所见,我们使用了添加 org.springframework 的 Servlet 声明。 web.servlet.DispatcherServlet 类,它将触发 MVC 模式的主要调度程序。作为附加声明,该标记将查找 XML 配置文件,在本例中为 WEB-INF/mvc-config.xml 。这个文件是一个 Spring 上下文配置。

最后看一下src/main/webapp/WEB-INF/mvc-config.xml中包含的Spring配置

  1. <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <bean name="/showMessage.html" class="com.apress.spring.SimpleController" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp" /> </bean> </beans>

这是标准的 Spring 配置,您可以在其中定义将实例化 Spring 容器的 bean。在这个配置文件中,有一个名为 /showMessage.html 的 bean 指向 com.example.SimpleController Java 类。这个特殊的声明是当有对 /showMessage.html URL 的请求时将映射到要执行的类的 URL。您还需要添加另外一个 bean 声明来定义您的视图。在这种情况下,每个视图都将放置在 /WEB-INF/view 文件夹中,并且每个页面都将具有 .jsp 扩展名。现在让我们看一下 SimpleController.java 类:

  1. package com.example;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;
  4. import org.springframework.web.servlet.ModelAndView;
  5. import org.springframework.web.servlet.mvc.AbstractController;
  6. public class SimpleController extends AbstractController {
  7. @Override
  8. protected ModelAndView handleRequestInternal(
  9. HttpServletRequest request, HttpServletResponse response) throws Exception {
  10. ModelAndView model = new ModelAndView("showMessage");
  11. model.addObject("message", "Spring MVC Web Application");
  12. return model;
  13. }
  14. }

此类扩展了 org.springframework.web.servlet.mvc.AbstractControlle 类,该类具有管理您的请求 ( /showMessage.html ) 的所有逻辑。在 handleRequestInternal 方法中,我们将返回一个 ModelAndView 实例,其中包含要显示的视图的信息。

最后,让我们组合视图,命名为“showMessage.jsp”,在 Controller 类中声明:(该文件将位于 /WEB-INF/view/showMessage.jsp)

  1. <!DOCTYPE html> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <head> <meta charset="utf-8" /> <title>Welcome</title> </head> <body> <h2>${message}</h2> </body> </html>

当您部署此应用程序时,Spring 将呈现“Spring MVC Web 应用程序”消息。

按如下方式打包您的应用程序:

  1. $ mvn clean package

这将创建 simple-mvc-app.war 应用程序,该应用程序可以部署在 Web 服务器/应用程序服务器上并通过以下方式进行测试:

http://localhost:8080/simple-mvc-app/showMessage.html URL,它将显示消息“Spring MVC Web Application”。

Spring MVC 2.5 及以上版本

在上面的示例中,您可能已经注意到我们对 Spring MVC 应用程序使用了一种旧方法。事实上,从 Spring MVC 2.5 版本开始,您可以添加注释以避免从其他类扩展,从而简化映射。考虑以下 SimpleController 类:

  1. package com.example;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RequestMethod;
  5. import org.springframework.web.servlet.ModelAndView;
  6. @Controller
  7. @RequestMapping("/showMessage.html")
  8. public class HelloWorldController {
  9. @RequestMapping(method = RequestMethod.GET)
  10. public ModelAndView helloWorld() {
  11. ModelAndView model = new ModelAndView("showMessage");
  12. model.addObject("message", "Spring MVC Web App with annotations");
  13. return model;
  14. }
  15. }

src/main/webapp/WEB-INF/mvc-config.xml 中所需的更改是:

  1. <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
  2. <context:component-scan base-package="com.example"/>
  3. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  4. <property name="prefix" value="/WEB-INF/view/"/>
  5. <property name="suffix" value=".jsp"/>
  6. </bean>
  7. </beans>

从上面的例子可以看出,现在我们使用一个标签告诉 Spring 引擎扫描所有标记有该包的类。在此示例中,它将找到 SimpleController 类,因为它已被 @Controller 注解标记。此外,您可能已经注意到所有 bean 定义都已从现在由 SimpleController 类处理的配置中删除。

Spring Boot Web 应用程序

现在是时候看看 Spring Boot 如何帮助您使用 MVC 模式创建 Web 应用程序了。我们将使用 Spring CLI 引导一个简单的 Web 应用程序模板,因此打开一个终端,创建一个文件夹 ( simple-mvc-spring-boot ),然后执行以下命令:

  1. $ mkdir simple-mvc-spring-boot $ cd simple-mvc-spring-boot $ spring init -d=web -g=com.example -a=simple-mvc-spring-boot --package-name=com.example -name=simple-mvc-spring-boot -x

此命令将为您的 Spring Boot Web 应用程序创建一个模板。

• -d=web 告诉 CLI 包含 web 启动器

• -g=com.example 是 groupId

• -a=simple-mvc-spring-boot 是 artifactId

• –package-name=com.example 是类的基本包名称

• -name=simple-mvc-spring-boot 是应用程序的名称

• -x 将提取当前目录中的模板;如果省略提取选项,您将找到一个 simple-mvc-spring-boot.zip 文件

您的文件结构应与以下类似:

  1. ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main    ├── java       └── com       └── example       └── SimpleMvcSpringBootApplication.java    └── resources    ├── application.properties    ├── static    └── templates └── test └── java └── com └── example └── SimpleMvcSpringBootApplicationTests.java

现在打开文件 SimpleMvcSpringBootApplication.java 并修改它看起来与

  1. package com.example;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.web.bind.annotation.RestController;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. @RestController
  7. @SpringBootApplication
  8. public class SimpleMvcSpringBootApplication {
  9. @RequestMapping("/hello.html")
  10. public String index() {
  11. return "Hello World Spring Boot MVC!";
  12. }
  13. public static void main(String[] args) {
  14. SpringApplication.run(SimpleMvcSpringBootApplication.class, args);
  15. }
  16. }

在这个修改后的应用程序中,我们用 @RestController 注释标记了 rest 控制器,并定义了一个用 @RequestMapping 标记的索引方法。此方法的目的是接受对 /hello.html URL 的所有传入请求。要运行它,只需执行以下命令:

  1. $ ./mvnw spring-boot:run

此命令将运行应用程序,因此请使用浏览器在默认 Web 服务器地址和端口上检查 http://localhost:8080/hello.html URL。您将看到消息:“Hello World Spring Boot MVC!”。

没有 Maven 的 Spring Boot

在上面的例子中例如,我们通过调用“spring init”命令从模板创建了一个 Spring Boot 应用程序。 您甚至可以创建一个无 Maven 的应用程序,它只使用最小的 @RequestController 和 @RequestMapping。 通过使用 groovy 作为语言,您甚至不需要标准类型的包声明:

  1. @RestController class WebApp {
  2. @RequestMapping("/hello.html") String greetings() {
  3. "Spring Boot MVC is easier"
  4. }
  5. }

您可以使用以下命令运行应用程序:

  1. $ spring run app.groovy

现在用浏览器检查: http://localhost:8080/hello.html 。 如您所见,我们摆脱了 maven、web.xml、bean 声明和任何类型的配置

结论

在本教程中,我们看到了 Spring MVC 应用程序的演变,以及 Spring Boot 如何使用这种很棒的模式极大地简化了 Web 应用程序的设计和开发。

相关文章