本節(jié)介紹SpringBoot創(chuàng)建第一個示例SSM項(xiàng)目的完整過程觅廓,使用工具STS衣形,與IDEA操作基本類似。
示例代碼在:https://github.com/laolunsi/spring-boot-examples
前言
根據(jù)幾位網(wǎng)友反饋的結(jié)果,重新編輯了這篇文章肋坚。此篇文章先從環(huán)境配置開始,然后到項(xiàng)目創(chuàng)建肃廓,最后講述SSM框架整合智厌,展現(xiàn)一個完整SpringBoot項(xiàng)目創(chuàng)建與使用的過程。
基于maven搭建直接SSM或者SSH框架的麻煩之處盲赊,被各種配置文件(尤其是xml)折磨的在座各位應(yīng)該深有體會铣鹏。而SpringBoot的出現(xiàn)正好解決了這個問題,拋棄各種繁瑣的配置哀蘑,我們只需要一個application.properties文件就可以解決這些問題诚卸。
下面進(jìn)入正題葵第。
一、環(huán)境搭建
首先下載一個專為Spring設(shè)計的eclipse版本——Spring Tool Suite合溺,簡稱STS卒密。它是Eclipse的一個特殊版本,界面和操作與Eclipse都非常類似棠赛,下載zip包可以直接運(yùn)行哮奇。
注:IDEA和STS創(chuàng)建springboot項(xiàng)目的步驟和界面是完全一樣的。創(chuàng)建的項(xiàng)目結(jié)構(gòu)也相近睛约,sts創(chuàng)建的項(xiàng)目可以直接導(dǎo)入IDEA使用鼎俘。
先看一下界面:
二、創(chuàng)建SpringBoot項(xiàng)目
解壓壓縮包后運(yùn)行下面的exe文件(上面有綠色圖標(biāo)的)辩涝,然后你會看到上面的界面贸伐。
然后點(diǎn)擊左上角,F(xiàn)ile——new——Spring Starter Project怔揩。下面是詳細(xì)步驟:
第一步捉邢,new——>Spring Starter Project.
接著,name填入項(xiàng)目名稱商膊,group隨意歌逢,其他的不用管,這里的service URL指Spring boot官網(wǎng)地址翘狱。
然后秘案,version默認(rèn)選擇,Available中輸入查找潦匈,選中以下五項(xiàng):Web阱高、DevTools、MySQL茬缩、Mybatis赤惊、Thymeleaf。
(注:這里的環(huán)境可以先不選凰锡,之后根據(jù)需要在maven的依賴配置文件pom.xml中添加即可未舟。我這里先行加上,等會兒一一介紹用途)掂为。
最后點(diǎn)擊next/finish均可裕膀,等待一會兒,項(xiàng)目創(chuàng)建完畢勇哗,目錄如下:
注:如果resources下的static或者templates文件夾不存在的話昼扛,不用著急,這個是因?yàn)槲疑厦孢x擇了那些依賴才創(chuàng)建的欲诺,后面手動加一下也沒關(guān)系抄谐。
三渺鹦、項(xiàng)目啟動
到目前為止,SpringBoot項(xiàng)目已經(jīng)創(chuàng)建完畢了蛹含。
我們可以看到啟動類SpringBootDemoApplication.java這個類毅厚。
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoApplication.class, args);
}
}
這個類是干嘛的呢?
我們看到其中有main方法浦箱。
沒錯吸耿,SpringBoot項(xiàng)目就是使用這個類啟動的,右擊這個類憎茂,run as——Spring Boot App,項(xiàng)目就會啟動锤岸。
這里有一個誤區(qū):為什么按照我這里步驟創(chuàng)建會報錯竖幔。
這是由于我之前選擇添加了Web等依賴,此時項(xiàng)目是無法直接執(zhí)行的——看控制臺日志就能看出是數(shù)據(jù)庫沒有配置的原因是偷。而如果我沒有添加這些依賴拳氢,直接運(yùn)行SpringBootWebApplication.java文件,就可以啟動項(xiàng)目了蛋铆。
下面馋评,我們講解一下環(huán)境配置的問題——配置完成后就可以運(yùn)行這個空的SSM項(xiàng)目了哦。
四刺啦、環(huán)境配置
4.1 maven之pom.xml
為什么要先講maven呢留特?
因?yàn)槲抑罢fSSM——Spring+SpringMVC+Mybatis項(xiàng)目。這個應(yīng)該是大家比較感興趣的——目前企業(yè)里這一類項(xiàng)目大多數(shù)都是SSM框架了玛瘸。以前很火的SSH現(xiàn)在被使用的并不多蜕青。說個盤外話,SSH真的坑糊渊。
看一下我的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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>SpringBootDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringBootDemo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- springboot推薦的模板引擎,要想映射HTML/JSP渺绒,必須引入thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- 熱部署用贺喝,改變代碼不需要重啟項(xiàng)目 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<!-- mysql連接 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
4.2 配置文件application.properties
SpringBoot項(xiàng)目的配置是基于application.properties這個文件的。在里面配置數(shù)據(jù)庫宗兼、Mybatis映射文件乃至更高級的Redis躏鱼、RabbitMQ等等(這里的配置文件重新修改過,github上為最新)殷绍。
注意:下面配置的數(shù)據(jù)庫地址挠他、賬號和密碼,必須完全與你本機(jī)一樣篡帕!如果你的數(shù)據(jù)庫賬號是其他名字殖侵,比如admin贸呢,請修改下面的配置。
# server config
server.port: 8081
# mysql
spring.datasource.url: jdbc:mysql://localhost:3306/umanager?useSSL=false&autoReconnect=true
spring.datasource.username: root
spring.datasource.password: root
spring.datasource.driver-class-name: com.mysql.jdbc.Driver
spring.datasource.dbcp2.validation-query: 'select 1'
spring.datasource.dbcp2.test-on-borrow: true
spring.datasource.dbcp2.test-while-idle: true
spring.datasource.dbcp2.time-between-eviction-runs-millis: 27800
spring.datasource.dbcp2.initial-size: 5
spring.datasource.dbcp2.min-idle: 5
spring.datasource.dbcp2.max-idle: 100
spring.datasource.dbcp2.max-wait-millis: 10000
# thymleaf
spring.thymeleaf.cache : false
# mybatis
mybatis.mapper-locations: classpath:mapper/*.xml
mybatis.configuration.map-underscore-to-camel-case: true
4.3 啟動項(xiàng)目
找到SpringBootDemoApplication類拢军,Run As——Spring Boot App楞陷,項(xiàng)目啟動成功,控制臺不報錯茉唉。
五固蛾、SpringBoot+SSM框架整合示例
第一步,建立數(shù)據(jù)庫——這個很重要哦度陆。根據(jù)我們在application.properties的配置建立數(shù)據(jù)庫及表艾凯,我這里使用了umanager數(shù)據(jù)庫,以及user表懂傀,下面貼上我的建庫建表語句:
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'ja', '123', '江蘇');
INSERT INTO `user` VALUES ('2', 'BL', '123', '新加坡');
第二步趾诗,創(chuàng)建BasicController.java(完整的項(xiàng)目目錄看最下面)
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.example.demo.model.bean.User;
import com.example.demo.model.dao.UserDAO;
// @RestController = @Controller + @ResponseBody
@RestController
public class BasicController {
@Autowired
private UserDAO userDAO;
@GetMapping(value = "")
public String index() {
return "login"; // 此處表示返回值是一個值為“l(fā)ogin”的String。不指向界面的原因是類的注解是@RestController
}
@GetMapping(value = "index.do")
public ModelAndView index2() {
return new ModelAndView("login"); // 此處指向界面
}
@GetMapping(value = "login.do")
public Object login(String name, String password) {
System.out.println("傳入?yún)?shù):name=" + name + ", password=" + password);
if (StringUtils.isEmpty(name)) {
return "name不能為空";
} else if (StringUtils.isEmpty(password)) {
return "password不能為空";
}
User user = userDAO.find(name, password);
if (user != null) {
return user;
} else {
return "用戶名或密碼錯誤";
}
}
}
這個類使用了User類和注入了UserDAO接口蹬蚁。我們同樣創(chuàng)建這兩個類:
public class User implements Serializable {
private static final long serialVersionUID = -5611386225028407298L;
private Integer id;
private String name;
private String password;
private String address;
// 省略get和set方法恃泪,大家自己設(shè)置即可
}
package com.example.demo.model.dao;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import com.example.demo.model.bean.User;
@Mapper
public interface UserDAO {
public User find(@Param("name")String name, @Param("password")String password);
// 注: CRTL+Shift+O,快捷導(dǎo)入所有import
}
下面還需要mybatis映射接口到SQL語句的文件犀斋,根據(jù)application.properties中的配置mybatis.mapper-locations: classpath:mapper/*.xml
,在resources文件夾下新建mapper文件夾贝乎,下面放入Mybatis的xml文件。
此處寫一個UserDAO.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.demo.model.dao.UserDAO">
<select id="find" resultType="com.example.demo.model.bean.User">
SELECT id, name, password, address from user where name = #{name} and password = #{password}
</select>
</mapper>
還需要一個login.html頁面叽粹,放在resources/templates文件夾下:
<!DOCTYPE html>
<html>
<!-- meta這一句指定編碼格式览效,能夠防止中文亂碼 -->
<meta charset="UTF-8" />
<head>
<title>登錄</title>
</head>
<body>
<form action="/login.do" method="GET">
用戶名:<input type="text" id="name" name="name" />
密碼: <input type="password" id="password" name="password" />
<input type="button" value="登錄" onclick="submit()" />
</form>
</body>
</html>
下面,我們來看一下項(xiàng)目目錄結(jié)構(gòu):

六虫几、啟動和測試
到目前為止朽肥,我們已經(jīng)在SpringBoot中整合了SSM框架,下面運(yùn)行看一下效果持钉。啟動Application類后衡招,控制臺無錯。在瀏覽器輸入:http://localhost:8081/
每强,看到如下界面:
這個
login
字符串始腾,就是請求http://localhost:8081/
經(jīng)BasicController處理獲得的。
下面測試一下登錄功能空执,輸入http://localhost:8081/index.do
浪箭,看到如下界面:
輸入你的數(shù)據(jù)庫user表中的一個正確用戶,點(diǎn)擊登錄辨绊,獲得如下示例數(shù)據(jù):
如果輸入錯誤的數(shù)據(jù)奶栖,則:
這說明SSM框架已經(jīng)整合成功了!我們的SpringBoot+SSM第一個示例也就圓滿完成!P伞袍镀!
交流學(xué)習(xí)
個人網(wǎng)站:http://www.eknown.cn
GitHub:https://github.com/laolunsi
公眾號:猿生物語,"分享技術(shù)冻晤,也感悟人生"苇羡,歡迎關(guān)注!