
2.2 使用IDEA创建Spring Boot项目
2.2.1 创建Spring Boot项目
创建Spring Boot项目的基本步骤如下所述。
(1)打开IDEA,单击【Create New Project】按钮,开始创建一个新项目,如图2-3所示。如果已经打开了IDEA,则选择【File】→【News】→【Project】命令,打开项目创建界面。

图2-3 创建一个新项目
(2)如图2-4所示,在项目创建界面左侧列表框中选择【Spring Initializr】选项,然后单击【Next】按钮。注意,这里IDEA默认使用【https://start.spring.io】提供的在线模板,所以需要保证网络畅通。当然,也可以选中下面的【Custom】单选按钮,并从指定的链接加载模板。

图2-4 项目创建界面
(3)在如图2-5所示的界面中按实际情况依次填写项目信息。在【Type】下拉列表中可以选择【Maven Project】或【Pom】选项,这里保持默认设置,在【Packaging】下拉列表中选择【War】选项,并分别设置【Group】【Artifact】【Package】,然后单击【Next】按钮。

图2-5 填写项目信息
(4)在如图2-6所示的界面中选择依赖库。首先从【Spring Boot】下拉列表中选择Spring Boot的版本,此处保持默认设置。然后在界面左侧列表框中选择大类,并在界面中间勾选需要的依赖所对应的复选框,这里选择了【Developer Tools】类别下的【Spring Boot DevTools】【Lombok】【Spring Configuration Processor】,【Web】类别下的【Spring Web】,以及【SQL】类别下的【JDBC API】和【MySQL Driver】。最后单击【Next】按钮。

图2-6 选择依赖库
(5)在如图2-7所示的界面中设置项目名称和存储位置,并在完成后单击【Finish】按钮。

图2-7 设置项目名称和存储位置
(6)在使用IDEA构建好项目后,项目结构如图2-8所示。

图2-8 项目结构
2.2.2 根据项目需要引入其他依赖
1.初始依赖说明
对于刚刚创建的项目而言,pom.xml文件的内容如下:



pom.xml文件中包含的依赖说明如下所述。
●spring-boot-starter-parent:作为父依赖,提供Spring Boot的默认配置和一棵完整的Spring Boot依赖树,还包括Maven的打包插件。它可以管理Spring Boot需要的依赖,从而统一各种jar包的版本号,避免了因版本不一致而出现的问题。所以,引入其他的依赖就可以省略版本号。当然也可以加上指定的版本号,从而取代默认的版本号。
●spring-boot-starter-jdbc:使用JDBC操作数据库的相关jar包。它可以根据配置自动创建数据源和JdbcTemplate对象。在程序中,可以通过注入JdbcTemplate对象来操作数据库,也可以在application.properties文件中配置数据源。
●spring-boot-starter-web:自动引入了Web模块开发需要的相关jar包。默认使用嵌套式的Tomcat作为Web容器对外提供HTTP服务,默认端口8080对外提供监听服务。若想改变默认的配置端口,则可以在application.properties文件中指定。
●spring-boot-devtools:支持热部署,提高开发者的开发效率。
●mysql-connector-java:MySQL驱动程序。
●spring-boot-configuration-processor:配置文件xml或properties、yml的处理器。
●lombok:提供了一组有用的标注,用来消除Java类中的大量样板代码,使得Java类更加简洁且易于维护。例如,@Data可生成setter/getter、equals、canEqual、hashCode、toString方法;@Slf4j注解在类上,可生成log变量。在IDEA编写源码时,需要先安装Lombok插件。
●spring-boot-starter-tomcat:在部署war包时,需要依赖此包。
2.引入其他依赖
修改pom.xml文件,引入依赖,以支持JSP,修改内容如下:


2.2.3 按分层结构组织程序结构
按分层结构组织程序,还需要建立其他包,这些包建立在com.rc包下,主要包括com.rc.controller(控制层包)、com.rc.dao(数据访问层接口包)、com.rc.dao.impl(数据访问层实现类包)、com.rc.service(业务逻辑层接口包)、com.rc.service.impl(业务逻辑层实现类包)、com.rc.entity(实体类包),结构如图2-9所示。

图2-9 包结构
Spring Boot默认使用的是Thymeleaf模板引擎,HTML网页存放在/resources/templates文件夹下,静态资源存放在resources/static文件夹下。在使用JSP时,不再使用这两个文件夹,而使用webapp文件夹。在webapp文件夹下创建WEB-INF文件夹,并在WEB-INF文件夹下创建jsp文件夹用于存放JSP网页,同时在webapp文件夹下创建static文件夹用于存放静态资源。
视图层的相关文件存放在WEB-INF/jsp文件夹下,在jsp文件夹下建立user(用户)、role(角色)、permission(权限)、application(应聘申请)、common(公共)、company(企业)、job(职位)、news(新闻)、person(个人)、upfiles(上传文件)文件夹,分别用于存放不同的网页文件。
在static文件夹下建立js(JavaScript)、css(样式表)、images(图像)文件夹,分别用于存放静态资源。
另外,在jsp文件夹中创建index.jsp作为系统首页,创建manage.jsp作为管理页。为了测试,可以在内容中先输入OK。视图层文件夹结构如图2-10所示。

图2-10 视图层文件夹结构
com.rc包下的两个类的说明如下所述。
RcApplication类中包含一个main()方法,是程序的启动类。它使用内置的Tomcat来部署程序。@SpringBootApplication标注用于完成自动配置。例如:

ServletInitializer类使用外部Tomcat来部署程序。在建立项目时,若选择打成war包,则会自动创建这个类。该类继承于SpringBootServletInitializer并实现了configure()方法,与原来的启动类配合,可完成自动配置。例如:

2.2.4 建立分页工具类
建立一个分页工具类PageHelper,代码如下:



2.2.5 应用程序基本配置
在application.properties文件中添加如下配置:
