Spring基础入门4 - Spring MVC

前面章节学习了Spring框架的IoC和AoP, 接下了学习使用Spring开发J2EE Web应用程序。一个J2EE Web应用程序需要符合J2EE的相关规范, 并部署运行在符合J2EE规范的容器中, 如(Apache Tomcat)。本文将简单的介绍Eclipse Web应用开发环境的构建。

开发环境:

  • JDK 8+
  • Eclipse IDE for Enterprise Java and Web Developers
  • Apache Tomcat 9.X

开发工具建议使用Eclipse for J2EE版本, 包含了所有需要的模块,将省去很多Eclipse额外的安装配置步骤。Apache的Tomcat做为J2EE Web Application的运行容器。Tomcat只需要解压即可,不需要额外配置,也不需要手动运行。

1. 定义一个J2EE Web Application Server

J2EE Web Application需要在J2EE Web容器中执行,我们先将本地的Apache Tomcat添加到Eclipse中,以便我们在Eclipse执行和调试我们的Web应用程序。注意,Server是Eclipse所有项目共用的。

走菜单"New" -> "Other…“添加, 弹出对话框中找到"Server”,执行添加向导。

  1. 服务器类型这里选"Apache Tomcat"

在这里插入图片描述
2. 指定服务器(Tomcat)的本地安装目录。

在这里插入图片描述

点击"Finish"即可完成配置。

2. 创建一个webapp类型的maven项目

Eclipse创建一个Maven的项目, ArcheType选择"maven-archetype-webapp", 完成向导后得到一个webapp maven项目。maven-archetype-webapp模板创建的项目的主要目录结构:

  - src/main/java          -- class(beans) root of the application;        // 应用相关类的更目录;
  - src/main/webapp    -- document root of the application;             // 应用网页(文档)的根目录;
  - src/test/java            -- test class(beans) root of the application; // 应用测试类创建的根目录;

在这里插入图片描述

3. 为项目添加"Server Runtime"

选择上述创建的项目,走右键菜单"Build Path -> Add Libraries…",弹出对话框中选择"Server Runtime", 下一步选择前面创建的Server即可。

4. 配置项目的pom.xml文件

需要引入相关依赖, 修改项目默认的编译版本。

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    ...
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<!-- Spring 5需要Java 8+ -->
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
	</properties>
	<dependencies>
		<!-- 引入相关依赖 --> 
		<!-- Spring mvc support -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>5.3.15</version>
		</dependency>
		<!-- jsp support, 包含servlet-api -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.0</version>
			<scope>provided</scope>
		</dependency>
		<!-- jstl support -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		...
	</dependencies>
	<build>
	    <!-- application url = http://host:port/onlinestore/ -->
		<finalName>onlinestore</finalName>
		<pluginManagement>
		...
		</pluginManagement>
	</build>
</project>

关于maven依赖的一些题外话:
依赖管理(Dependency management)是Maven的核心特性, 当我们的项目包含多个模块时,Maven可以简化我们对依赖库的管理。 通过https://repo1.maven.org/上看spring-webmvc的pom.xml文件, 可以看到spring-mvc也包含依赖:

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>5.3.15</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>5.3.15</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.15</version>
      <scope>compile</scope>
    </dependency>
 	...
  </dependencies>

Maven的依赖是具有传递性的(Transitive Dependencies),当我们引入了spring-webmvc模块,也会将spring-core, spring-aop, spring-beans,spring-context,…引入到我们的maven项目中,所以我们仅需要添加spring-webmvc依赖就可以了。整个maven项目依赖库和版本的管理都交由maven解析处理的,我们可以通过mvn dependency:tree列出项目的依赖树:

C:\Users\Think\eclipse-workspace\learning2>mvn dependency:tree
[INFO] Scanning for projects...
[INFO]
[INFO] ----------------------< org.littlestar:learning2 >----------------------
[INFO] Building learning2 Maven Webapp 1
[INFO] --------------------------------[ war ]---------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ learning2 ---
[INFO] org.littlestar:learning2:war:1
[INFO] +- org.springframework:spring-webmvc:jar:5.3.15:compile
[INFO] |  +- org.springframework:spring-aop:jar:5.3.15:compile
[INFO] |  +- org.springframework:spring-beans:jar:5.3.15:compile
[INFO] |  +- org.springframework:spring-context:jar:5.3.15:compile
[INFO] |  +- org.springframework:spring-core:jar:5.3.15:compile
[INFO] |  |  \- org.springframework:spring-jcl:jar:5.3.15:compile
[INFO] |  +- org.springframework:spring-expression:jar:5.3.15:compile
[INFO] |  \- org.springframework:spring-web:jar:5.3.15:compile
[INFO] +- javax.servlet:jsp-api:jar:2.0:provided
[INFO] |  \- javax.servlet:servlet-api:jar:2.4:provided
[INFO] +- javax.servlet:jstl:jar:1.2:compile
[INFO] \- junit:junit:jar:4.11:test
[INFO]    \- org.hamcrest:hamcrest-core:jar:1.3:test
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  1.610 s
[INFO] Finished at: 2022-01-24T11:28:14+08:00
[INFO] ------------------------------------------------------------------------

查看依赖树的另一个方法是通过Eclipse打开项目的pom.xml文件,在"Dependency Hierarchy"页也可以看到:
在这里插入图片描述
当我们项目的依赖出现冲突时,我们需要对依赖树进行分析和排除。

5. 执行Web应用

选择我们的项目, 右键菜单"Run As -> Run on Server",看到"Hello World!"页面说明开发的基础环境已经搭建好。

6. 关于J2EE Web applications

如果你和我一样之前对Web应用没有多少了解,还是个小白,可以参考下面的介绍。介绍摘抄自于某产品的文档,个人觉得介绍的很好,分享给大家:https://www.ibm.com/docs/en/configurepricequote/9.4.0?topic=implementing-introduction-j2ee-web-applications

Web applications
A J2EE Web application is built to conform to a J2EE specification. You add Web components to a J2EE servlet container in a package called a Web application archive (WAR) file. A WAR file is a JAR (Java archive) file compressed file.

A WAR file usually contains other resources besides Web components, including:

  • Server-side utility classes
  • Static web resources (configuration files, HTML pages, image and sound files, and so on)
  • Client-side classes (applets and utility classes)

The directory and file structure of a Web application deployed as a WAR file conforms to a precise structure. A WAR file has a specific hierarchical directory structure. The top-level directory of a WAR file is the document root of the application. The document root is the directory under which JSP pages, client-side classes and archives, and static Web resources are stored. The document root contains a subdirectory called WEB-INF/, which contains the following files and directories:

  • web.xml: the Web application deployment descriptor. It describes the structure of the Web application.
  • Tag library descriptor files.
  • classes/: a directory that contains server-side classes: servlet, utility classes, and Java Beans components.
  • lib/: a directory that contains JAR archives of libraries (tag libraries and any utility libraries called by server-side classes).

web.xml file
Every Web application deployed in a servlet container must have a web.xml file present in its WEB-INF/ directory. The structure of every web.xml conforms to a DTD published as part of the J2EE specification.

The purpose of the web.xml is to specify the general configuration of the Web application as required by the J2EE standard. Specifically:

  • initialization parameter values are provided for the Web application
  • servlet classes used by the Web application may be declared and given names
  • each servlet class is mapped to one or more URL patterns: when the servlet container receives a request whose URL matches a pattern defined in the web.xml file, then the corresponding servlet is used to process the request
  • initialization parameter values are provided for each servlet if required
  • session information (such as time out)
  • the location of custom tag libraries used by the JSP pages

JSP pages
Early Java-based Web applications used only servlets to generate the HTML that was sent back to users’ Web browsers. Over time, template mechanisms were introduced that enabled Web developers to generate dynamic content by using templates to generate the HTML. Several such template systems are available, however the J2EE architecture has settled on the use of JSP (JavaServer pages) pages to display content.

When a J2EE application receives a request from a user’s browser, it first processes the request to extract parameters from the request and to perform business logic initiated by the request. Once the processing is complete, the Web application must dispatch the request to a JSP page: it does this by using a request dispatcher. Typically, the servlet context invokes a request dispatcher by passing the target JSP page to the dispatcher and then the request and response objects are forwarded by the request dispatcher.

  • A JSP page comprises a combination of HTML, JSP tags, and scripting elements such as scriptlets.
  • HTML: a JSP page can include any amount of normal HTML. This content is passed right through to the browser page without change.
  • JSP tags: tags populate the dynamically-generated HTML with values calculated as the page is being generated. There are standard JSP tags such as jsp:getProperty, jsp:include, and jsp:forward. These are available to anyone creating a JSP page. In addition, you can specify that your Web application uses one or more custom tag libraries. Each custom tag library must be declared in the web.xml file for the Web application and the declaration must specify both the URI for the tag library and the location of the tag library descriptor (TLD) file.
  • Scripting elements: You can intersperse the HTML and JSP tags in a JSP page with Java code that is contained between the scriptlet opening tag <% (or jsp:scriptlet) and the closing tag %> (or </jsp:scriptlet>). Scriptlets are most commonly used to manage complex flow control in a JSP page.

Data is passed to a JSP page using a variety of mechanisms, the most important of which are implicit objects and beans.

  • Implicit objects: Every JSP page provides the Web developer with objects that can be used to display data on the generated HTML page. The most important of these are the page, request, session, config, and application objects.

  • Beans: Most of the data generated by the business logic of the application is passed to the JSP page by adding Java beans to one of the implicit objects listed above.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值