
2.2 使用Eclipse开发Spring入门程序
本节将通过一个简单的入门程序向读者演示Spring框架的使用过程,使读者深入了解Spring的内容,具体过程如下。
2.2.1 新建Maven项目

将Eclipse、Tomcat、Maven等环境配置成功之后,新建Maven项目的具体操作步骤如下。
步骤1:启动Eclipse后,选择File→New→Maven Project命令,如图2-2所示。

图2-2 新建Maven项目
步骤2:在弹出的New Maven Project对话框中勾选Create a simple project,单击Next按钮,如图2-3所示。
步骤3:在对话框中填写Group Id和Artifact Id信息,如图2-4所示。
提示:Group Id定义了项目属于哪个组,举个例子,如果公司mycom有一个项目myapp,那么Group Id就应该是com.mycom.myapp。Artifact Id定义了当前Maven项目在组中唯一的ID,如myapp-util、myapp-domain、myapp-web等。Version指定了myapp项目的当前版本。Name声明了一个对用户更友好的项目名称,不是必须的,推荐为每个项目声明name,以方便信息交流。
步骤4:项目信息填写完成,单击Finish按钮。选择新建的项目helloWorld,右击,在弹出的快捷菜单中选择Properties命令,如图2-5所示。
步骤5:在Properties for helloWorld对话框中选择Resource,在Resource窗口中选择Other,在下拉列表框中选择UTF-8,如图2-6所示。

图2-3 勾选Create a simple project

图2-4 填写项目信息

图2-5 选择Properties命令

图2-6 选择UTF-8编码
提示:GBK是在国家标准GB 2312基础上扩容后兼容GB 2312的标准,GBK编码是用双字节表示的。UTF-8编码包含全世界所有国家需要用到的字符,它对英文使用8位(即一个字节)编码,对中文使用24位(三个字节)编码。对于英文字符较多的论坛,使用UTF-8编码可以节省空间。另外,如果外国人访问GBK编码的网页需要下载中文语言包支持,访问UTF-8编码的网页则不需要。为了避免出现乱码,程序开发时一般用UTF-8编码。
步骤6:在Properties for helloWorld对话框中选择Maven→Project Facets,在Project Facets窗口中勾选Dynamic Web Module,其目的是使Java项目可以转换为Web项目,如图2-7所示。

图2-7 勾选Dynamic Web Module
步骤7:在Properties for helloWorld对话框中选择Targeted Runtimes,在Targeted Runtimes窗口中勾选Apache Tomcat v9.0,如图2-8所示。

图2-8 勾选Apache Tomcat v9.0
2.2.2 搭建Spring框架

Maven项目建立完成,下面开始搭建Spring框架,具体的操作步骤如下。
步骤1:添加Spring框架依赖的jar包,在pom.xml文件中设置依赖即可,如图2-9所示。

图2-9 添加Spring框架依赖的jar包
代码如下:



步骤2:将pom.xml文件导入jar后,为Spring框架添加web.xml文件进行配置。在src/main文件夹中新建文件夹webapp,在webapp文件夹中新建WEB-INF文件夹,并在WEB-INF文件夹中新建一个XML文件,文件名为web.xml,在该文件中进行相关配置,如图2-10所示。

图2-10 新建web.xml文件
代码如下:

步骤3:web.xml文件配置完成后,需要在src/main/resources中新建一个文件夹spring,在spring文件夹中新建一个XML配置文件,文件名为spring-context.xml,在该文件中进行相关配置,如图2-11所示。

图2-11 新建spring-context.xml文件
代码如下:

步骤4:spring-context.xml文件配置完成后,在src/main/resources/spring中新建一个XML配置文件,文件名为spring-mvc.xml,在该文件中进行相关配置,如图2-12所示。

图2-12 新建spring-mvc.xml文件
代码如下:

步骤5:spring-mvc.xml文件配置完成后,需要在src/main/java中新建一个包,包名为com.test.controller,右击com.test.controller选择new→class命令新建类,类名为TestController,如图2-13所示。

图2-13 新建类TestController
代码如下:

步骤6:在src/main/webapp下新建文件夹view,在view文件夹下新建test-jsp.jsp文件,如图2-14所示。

图2-14 新建test-jsp.jsp文件
代码如下:

步骤7:Spring框架搭建完成,右击运行按钮,未提示错误信息,在浏览器地址栏中输入localhost:8080/helloWorld/查看运行结果,如图2-15所示。

图2-15 运行结果
提示:运行项目时,注意使用Tomcat运行,如果不确定是否在配置Tomcat时选择使用Tomcat运行项目,则选择Eclipse下面的绿色按钮运行。