SpringBoot項目建立與第一個SSM項目示例

本節介紹SpringBoot建立第一個示例SSM項目的完整過程,使用工具STS,與IDEA操做基本相似。html

示例代碼在:https://github.com/laolunsi/spring-boot-examplesjava


前言

根據幾位網友反饋的結果,從新編輯了這篇文章。此篇文章先從環境配置開始,而後到項目建立,最後講述SSM框架整合,展示一個完整SpringBoot項目建立與使用的過程。mysql

基於maven搭建直接SSM或者SSH框架的麻煩之處,被各類配置文件(尤爲是xml)折磨的在座各位應該深有體會。而SpringBoot的出現正好解決了這個問題,拋棄各類繁瑣的配置,咱們只須要一個application.properties文件就能夠解決這些問題。git

下面進入正題。github


1、環境搭建

首先下載一個專爲Spring設計的eclipse版本——Spring Tool Suite,簡稱STS。它是Eclipse的一個特殊版本,界面和操做與Eclipse都很是相似,下載zip包能夠直接運行。
注:IDEA和STS建立springboot項目的步驟和界面是徹底同樣的。建立的項目結構也相近,sts建立的項目能夠直接導入IDEA使用。web

先看一下界面:
filespring


2、建立SpringBoot項目

解壓壓縮包後運行下面的exe文件(上面有綠色圖標的),而後你會看到上面的界面。
而後點擊左上角,File——new——Spring Starter Project。下面是詳細步驟:
第一步,new——>Spring Starter Project.
filesql

接着,name填入項目名稱,group隨意,其餘的不用管,這裏的service URL指Spring boot官網地址。
file數據庫

而後,version默認選擇,Available中輸入查找,選中如下五項:Web、DevTools、MySQL、Mybatis、Thymeleaf。
(注:這裏的環境能夠先不選,以後根據須要在maven的依賴配置文件pom.xml中添加便可。我這裏先行加上,等會兒一一介紹用途)。
fileapache

最後點擊next/finish都可,等待一下子,項目建立完畢,目錄以下:
file

注:若是resources下的static或者templates文件夾不存在的話,不用着急,這個是由於我上面選擇了那些依賴才建立的,後面手動加一下也不要緊。


3、項目啓動

到目前爲止,SpringBoot項目已經建立完畢了。
咱們能夠看到啓動類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項目就是使用這個類啓動的,右擊這個類,run as——Spring Boot App,項目就會啓動。
這裏有一個誤區:爲何按照我這裏步驟建立會報錯。
這是因爲我以前選擇添加了Web等依賴,此時項目是沒法直接執行的——看控制檯日誌就能看出是數據庫沒有配置的緣由。而若是我沒有添加這些依賴,直接運行SpringBootWebApplication.java文件,就能夠啓動項目了。
下面,咱們講解一下環境配置的問題——配置完成後就能夠運行這個空的SSM項目了哦。


4、環境配置

4.1 maven之pom.xml

爲何要先講maven呢?
由於我以前說SSM——Spring+SpringMVC+Mybatis項目。這個應該是你們比較感興趣的——目前企業裏這一類項目大多數都是SSM框架了。之前很火的SSH如今被使用的並很少。說個盤外話,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>

        <!-- 熱部署用,改變代碼不須要重啓項目  -->
        <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項目的配置是基於application.properties這個文件的。在裏面配置數據庫、Mybatis映射文件乃至更高級的Redis、RabbitMQ等等(這裏的配置文件從新修改過,github上爲最新)。
注意:下面配置的數據庫地址、帳號和密碼,必須徹底與你本機同樣!若是你的數據庫帳號是其餘名字,好比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 啓動項目

找到SpringBootDemoApplication類,Run As——Spring Boot App,項目啓動成功,控制檯不報錯。
file


5、SpringBoot+SSM框架整合示例

第一步,創建數據庫——這個很重要哦。根據咱們在application.properties的配置創建數據庫及表,我這裏使用了umanager數據庫,以及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', '新加坡');

第二步,建立BasicController.java(完整的項目目錄看最下面)

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"; // 此處表示返回值是一個值爲「login」的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("傳入參數: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接口。咱們一樣建立這兩個類:

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方法,你們本身設置便可
}
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,快捷導入全部import
}

下面還須要mybatis映射接口到SQL語句的文件,根據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>

下面,咱們來看一下項目目錄結構:
在這裏插入圖片描述
file


6、啓動和測試

到目前爲止,咱們已經在SpringBoot中整合了SSM框架,下面運行看一下效果。啓動Application類後,控制檯無錯。在瀏覽器輸入:http://localhost:8081/,看到以下界面:
filefile
這個login字符串,就是請求http://localhost:8081/經BasicController處理得到的。

下面測試一下登陸功能,輸入http://localhost:8081/index.do,看到以下界面:
file

輸入你的數據庫user表中的一個正確用戶,點擊登陸,得到以下示例數據:
file

若是輸入錯誤的數據,則:
file

這說明SSM框架已經整合成功了!咱們的SpringBoot+SSM第一個示例也就圓滿完成!!!


交流學習

我的網站:http://www.eknown.cn

GitHub:https://github.com/laolunsi

公衆號:猿生物語,"分享技術,也感悟人生",歡迎關注!

相關文章
相關標籤/搜索