手把手教你从0搭建SpringBoot项目

在银行呆了一年,很久没写SpringBoot项目了,搭建一个简单的SpringBoot项目回顾下

用到的工具:idea 2021、Maven 3.6.3、postman

框架:SpringBoot、Mybatis

数据库:Mysql8.0.30

一、Maven 安装&配置

安装&配置参考博文

注意:

1.下载maven注意idea与Maven版本的适配:

	IDEA 2022 兼容maven 3.8.1及之前的所用版本
	IDEA 2021 兼容maven 3.8.1及之前的所用版本
	IDEA 2020 兼容Maven 3.6.3及之前所有版本
	IDEA 2018 兼容Maven3.6.1及之前所有版本

2.为了避免每次创建项目都要改Maven配置,可以修改idea创建新项目的设置

二、安装数据库

mysql8安装参考博文

三、设计库表(这里用的idea自带的数据库管理工具,其他诸如Dbeaver、SQLyog等也可以)


**注意:**连接不上往往是驱动的问题,把对应的驱动下载好即可

新建表

新建字段

添加数据

注意:添加完成后需要提交

  • 添加的快捷键:alt+insert
  • 提交的快捷键:ctrl+enter

四、搭建SpringBoot项目

1.创建项目


2. 勾选会用到的依赖


3.项目刚创建好时的结构(图片是拷贝的别人的,所以项目名不一致,别在意,重点关注项目结构即可)

4.templates文件下新建index.html页面,作为启动的初始页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
SpringBoot 简单启动页面
</body>
</html>

5. 在com.susu.testsimplespringboot下新建controller文件夹,在controller文件夹下建一个简单的LoginController类;(Controller类要添加@Controller注解,项目启动时,SpringBoot会自动扫描加载Controller)


package com.susu.testsimplespringboot;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @ClassName HelloController
 * @Description TODO
 * @Author susu
 * @Date 2023/4/9 15:53
 * @Version 1.0
 */
@Controller
public class HelloController {

    @RequestMapping("/index")
    public String sayHello() {
        return "index";
    }
}

6.在resources文件夹下application中先配置DataSource基本信息

application文件有两种文件格式,一种是以**.properties为后缀,一种是以 .yml**为后缀的,两种配置方式略有差别,详情可参考:https://blog.csdn.net/qq_29648651/article/details/78503853;在这我是用.yml后缀的文件格式。右键application文件选择Refact,选择Rename,将后缀改为yml;

spring:
  datasource:
    name: test
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.susu.testsimplespringboot.DTO.UserLoginDTO

7. 运行项目TestSimpleSpringBootApplication.java(图片是拷贝的,所以文件名不一致,别在意,重点关注启动类没动过,直接启动即可)

8.在浏览器中输入localhost:8080,回车显示初始的index界面

9. SpringBoot 项目大概可以分为以下四层

  • mapper层(dao层)
  • service层(包括service接口、实现类)
  • controller层(web层)

10.最终的项目结构

11 项目代码展示

(1)在application配置文件中添加:数据库配置、MyBatis配置:

spring:
  datasource:
    name: test
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.susu.testsimplespringboot.DTO.UserLoginDTO

(2)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">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.10</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.susu</groupId>
    <artifactId>testSimpleSpringBoot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>testSimpleSpringBoot</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <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>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.3.0</version>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</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>

(3) 实体类

UserLogin

package com.susu.testsimplespringboot.pojo;

/**
 * @ClassName UserLogin
 * @Description TODO
 * @Author susu
 * @Date 2023/4/9 16:25
 * @Version 1.0
 */
public class UserLogin {
    private String userAccount;
    private String userPwd;

    public String getUserAccount() {
        return userAccount;
    }

    public void setUserAccount(String userAccount) {
        this.userAccount = userAccount;
    }

    public String getUserPwd() {
        return userPwd;
    }

    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }

    @Override
    public String toString() {
        return "UserLogin{" +
                "userAccount='" + userAccount + '\'' +
                ", userPwd='" + userPwd + '\'' +
                '}';
    }
}

UserLoginDTO (本质也是实体类,这里使用的原因是:数据库三个字段,实体类pojo中只有两个,无法映射,所以根据数据表添加一个三个属性的实体类DTO接收查询结果)

package com.susu.testsimplespringboot.DTO;

/**
 * @ClassName UserLoginDTO
 * @Description TODO
 * @Author susu
 * @Date 2023/4/9 16:49
 * @Version 1.0
 */
public class UserLoginDTO {
    private int userNo;
    private String userAccount;
    private String userPwd;

    public int getUserNo() {
        return userNo;
    }

    public void setUserNo(int userNo) {
        this.userNo = userNo;
    }

    public String getUserAccount() {
        return userAccount;
    }

    public void setUserAccount(String userAccount) {
        this.userAccount = userAccount;
    }

    public String getUserPwd() {
        return userPwd;
    }

    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }
}

(4)mapper接口

package com.susu.testsimplespringboot.mapper;

import com.susu.testsimplespringboot.DTO.UserLoginDTO;
import org.apache.ibatis.annotations.Mapper;

/**
 * @ClassName UserMapper
 * @Description TODO
 * @Author susu
 * @Date 2023/4/9 16:27
 * @Version 1.0
 */
@Mapper
public interface UserMapper {
    public abstract UserLoginDTO selectUserInfo(String userAccount, String userPwd);
}

(5)mapper映射文件(这个文件可以设置成idea自动提示的模板,避免每次都要自己写,方法如下图)

<?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.susu.testsimplespringboot.mapper.UserMapper">

    <!--验证用户账号和密码-->
    <select id="selectUserInfo" parameterType="String" resultType="com.susu.testsimplespringboot.DTO.UserLoginDTO">
        SELECT * FROM userLogin
        WHERE userAccount = #{userAccount}
          AND userPwd = #{userPwd};
    </select>


</mapper>


注意!!!

  1. namespace、id的属性值

    namespace :mapper接口名;
    id:mapper接口中抽象方法的名字

  2. mybatis映射文件的一些技术点可参考下面的博文
    https://blog.csdn.net/zxdspaopao/article/details/112919320

(6)service接口

package com.susu.testsimplespringboot.service;

import com.susu.testsimplespringboot.pojo.UserLogin;

/**
 * @ClassName UserService
 * @Description TODO
 * @Author susu
 * @Date 2023/4/9 16:27
 * @Version 1.0
 */
public interface UserService {

    public abstract UserLogin loginCheck(String userAccount, String userPwd);

}

(6)service实现类

package com.susu.testsimplespringboot.serviceImpl;

import com.susu.testsimplespringboot.DTO.UserLoginDTO;
import com.susu.testsimplespringboot.service.UserService;
import com.susu.testsimplespringboot.mapper.UserMapper;
import com.susu.testsimplespringboot.pojo.UserLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ClassName UserServiceImpl
 * @Description TODO
 * @Author susu
 * @Date 2023/4/9 16:37
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserLogin loginCheck(String userAccount, String userPwd) {
        UserLoginDTO userLoginDTO = userMapper.selectUserInfo(userAccount, userPwd);
        UserLogin userLogin = new UserLogin();
        if (userLoginDTO != null) {
            userLogin.setUserAccount(userLoginDTO.getUserAccount());
            userLogin.setUserPwd(userLoginDTO.getUserPwd());
        }
        return userLogin;
    }
}

(7)到此时,可以在测试类测试下Mapper层是否可以正常获取数据

package com.susu.testsimplespringboot;

import com.susu.testsimplespringboot.pojo.UserLogin;
import com.susu.testsimplespringboot.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;


@SpringBootTest
class TestSimpleSpringBootApplicationTests {

    @Autowired
    UserService userService;

    @Test
    void contextLoads() {
        UserLogin userLogin = userService.loginCheck("huahua", "123");
        System.out.println(userLogin);
    }

}

(8)controller

package com.susu.testsimplespringboot.controller;

import com.susu.testsimplespringboot.DTO.UserLoginDTO;
import com.susu.testsimplespringboot.pojo.UserLogin;
import com.susu.testsimplespringboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * @ClassName LoginController
 * @Description TODO
 * @Author susu
 * @Date 2023/4/9 16:27
 * @Version 1.0
 */
@Controller
//@ResponseBody
public class LoginController {

    @Autowired
    UserService userService;


    /**
     * @param testGetStaticSource
     * @param index
     * @return
     */
    @RequestMapping("{testGetStaticSource}/{index}")
    public String getStaticSource(@PathVariable String testGetStaticSource, @PathVariable String index) {
        return testGetStaticSource + "/" + index;
    }

    @GetMapping(value = "login")
    public String login() {
        return "login";
    }

    @GetMapping(value = "loginIn")
    public String loginGet(String userAccount, String userPwd) {
        UserLogin user1 = userService.loginCheck(userAccount, userPwd);
        if (user1 != null) {
            return "success";
        } else {
            return "error";
        }
    }

    @PostMapping(value = "loginIn")
    public String loginPost(UserLoginDTO userLoginDTO) {
        UserLogin user1 = userService.loginCheck(userLoginDTO.getUserAccount(), userLoginDTO.getUserPwd());
        if (user1 != null) {
            return "success";
        } else {
            return "error";
        }
    }

}

注意:

1.@RequestMapping,任何请求方式都可以

2.@GetMapping,只能Get请求(前端请求方式如下所示)

3.@PostMapping,只能Post请求

3.1 用postman发送post请求参考博文

3.2前端json格式报文:

{
"userAccount":"huahua",
"userPwd":"123"
}

4.测试了获取templates文件下的静态资源

    @RequestMapping("{testGetStaticSource}/{index}")
    public String getStaticSource(@PathVariable String testGetStaticSource, @PathVariable String index) {
        return testGetStaticSource + "/" + index;
    }

细节可以参考如下两篇博文
https://blog.csdn.net/zhuzicc/article/details/105465814#问题原因

https://blog.csdn.net/weixin_53106424/article/details/123502419

此处涉及springmvc的原理:

可以参考博文:
https://blog.csdn.net/weixin_53106424/article/details/115309018?spm=1001.2014.3001.5502

(9)几个静态文件

9.1 login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login</title>
</head>
<body>
<form role="form" action="/loginIn" method="post">
    账号:<input type="text" id="userAccount" name="userAccount"><br>
    密码:<input type="password" id="userPwd" name="userPwd"><br>
    <input type="submit" id="login" value="login">
</form>
</body>
</html>

9.2 success.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>success</title>
</head>
<body>
<h1>登录成功</h1>
</body>
</html>

9.3 error.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>eoor</title>
</head>
<body>
<h1>登录失败</h1>
</body>
</html>
相关推荐
测开小菜鸟22 分钟前
使用python向钉钉群聊发送消息
java·python·钉钉
P.H. Infinity1 小时前
【RabbitMQ】04-发送者可靠性
java·rabbitmq·java-rabbitmq
生命几十年3万天1 小时前
java的threadlocal为何内存泄漏
java
caridle2 小时前
教程:使用 InterBase Express 访问数据库(五):TIBTransaction
java·数据库·express
^velpro^2 小时前
数据库连接池的创建
java·开发语言·数据库
苹果醋32 小时前
Java8->Java19的初步探索
java·运维·spring boot·mysql·nginx
秋の花2 小时前
【JAVA基础】Java集合基础
java·开发语言·windows
小松学前端2 小时前
第六章 7.0 LinkList
java·开发语言·网络
Wx-bishekaifayuan2 小时前
django电商易购系统-计算机设计毕业源码61059
java·spring boot·spring·spring cloud·django·sqlite·guava
customer082 小时前
【开源免费】基于SpringBoot+Vue.JS周边产品销售网站(JAVA毕业设计)
java·vue.js·spring boot·后端·spring cloud·java-ee·开源