Spring Boot + Mybatis 項目搭建和登錄注冊例子


開發工具:IntelliJ IDEA
數據庫:MySql

目錄

Spring + Spring MVC + Mybatis 項目搭建和登錄注冊例子

Spring Boot + Mybatis 項目搭建和登錄注冊例子

Spring + Spring MVC + Hibernate 項目搭建和登錄注冊例子

Spring Boot + Hibernate 項目搭建和登錄注冊例子

Spring Boot 使用 JWT

本篇將記錄創建一個 Spring Boot + Mybatis 項目,並且編寫一個注冊登錄的例子,畢竟Java的東西配置起來真有點麻煩

創建數據庫

就隨便一點吧,使用MySql,數據庫就用 test ,新建一個 users 表,隨便設置幾個字段

注意

  1. 要按照命名規范,單詞均小寫,不同單詞之間使用下划線隔開
  2. Mybatis 貌似不推薦使用外鍵,需要我們在代碼中手動控制實體之間的關系
    其實是我在使用 Hibernate 和 Mybatis 的時候,用了很多時間都沒解決外鍵的問題,寫配置也覺得挺麻煩的
    感覺有時候不如自己封裝JDBC,只能感嘆 Entity Framework Core 是真的好用(貌似 Mybatis 的外鍵和 EF Core蠻像的),大概是我還太菜了吧,等我有時間解決外鍵的問題再寫另一篇記錄吧 T_T

IDEA 添加數據庫

輸入用戶名和密碼,填寫連接字符串,然后點擊 Test Connection,Schema 可以選擇連接的數據庫
連接字符串參考:jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false

創建項目

注意:有可能因為網絡問題創建不成功,可以使用代理網絡或者手機熱點試試

新建項目,選擇 Spring Initializr,JDK 一般都是1.8吧,因為只是例子,所以我就隨便選一個版本了

Group:一般的是域名
Artifact:項目名稱

因為是例子,所以我隨便起名了,然后Next

可以選擇一些需要的庫,也可以之后用Maven添加,這里我就選這幾個,然后Next
吐槽:還是NuGet方便,其實就是我懶

到這里其實只需要改一個路徑就好了,路徑最后的文件夾名稱一定要和項目名稱一致,然后就創建了

配置Maven,這里就不詳細展開講了,Maven的配置 baidu bing之類的搜索引擎隨便查都有答案

創建完項目,右鍵 src

修改 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.4.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com</groupId>
    <artifactId>springboot_mybatis_demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot_mybatis_demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <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.1.4</version>
        </dependency>

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

tomcat

這次就使用一一次 Spring Boot 內置的 tomcat 吧,外置的 tomcat 在 Spring Boot + Hibernate 中用過了

Spring Boot + Hibernate 項目搭建和登錄注冊例子:https://www.cnblogs.com/zzy-tongzhi-cnblog/p/14402297.html

也可以自己去 baidu bing 啥的找答案

application.properties 配置文件中設置

# 配置 Web 容器的端口號(默認為 8080)
# server.port=
# 配置當前項目出錯時跳轉去的頁面。
# server.error.path=
# 配置 session 失效時間。30m 表示 30 分鍾,如果不寫單位則默認單位是秒。(注意:由於 Tomcat 中配置 session 過期時間是以分鍾為單位,如果我們這里設置是秒的話,那么會自動轉換為一個不超過所配置秒數的最大分鍾數。比如配置了 119 秒,那么實際 session 過期時間是 1 分鍾)
# server.servlet.session.timeout=
# 配置項目名稱(默認為 /),如果配置了項目名稱,那么在訪問路徑中要加上配置的路徑
# server.servlet.context-path=
# 配置 Tomcat 請求編碼
# server.tomcat.uri-encoding=
# 配置 Tomcat 的最大線程數
# server.tomcat.max-threads=
# 配置 Tomcat 運行日志和臨時文件的目錄。若不配置,則默認使用系統的臨時目錄。
# server.tomcat.basedir=
# 配置 Servlet

#配置程序端口,默認為8080
server.port= 8080
# 配置默認訪問路徑,默認為/
server.servlet.context-path=/springboot_mybatis_demo

# 配置Tomcat編碼,默認為UTF-8
server.tomcat.uri-encoding=UTF-8
# 配置最大線程數
server.tomcat.max-threads=1000

# 數據庫
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456

# 視圖
# 編碼
spring.thymeleaf.encoding=UTF-8
# 前綴
spring.thymeleaf.prefix=classpath:/templates/Views/
# 后綴
spring.thymeleaf.suffix=.html

項目結構

  • Controllers:控制器
  • DAO:數據庫訪問
  • Filters:過濾器
  • Models:實體模型類
  • Services:服務層
  • Utils:工具類
  • Mappers:映射 xml 文件
  • Generator:Mybatis Generator 配置文件
  • Views:視圖

主頁

HomeController ,因為是主頁,所以我直接給方法標注 @RequestMapping("/") ,這樣只需要輸入項目名就可以轉到主頁
至於返回是 ModelAndView ,純粹是我懶得寫前端代碼,其實可以返回任何你想返回的類型,靠前端去處理

@RestController
public class HomeController
{
    @RequestMapping("/")
    public ModelAndView Index()
    {
        ModelAndView mav=new ModelAndView();
        mav.setViewName("Home/Index");

        return mav;
    }
}

Views/Home/Index.html ,這個路徑要根據 application.properties 配置文件修改

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link href="http://localhost:8080/springboot_mybatis_demo/css/MyStyleSheet.css" type="text/css" rel="stylesheet">
    <title>Index</title>
</head>
<body>
<h1>
    This is Home Index Page
</h1>
</body>
</html>

注意

  • http://localhost:8080/springboot_mybatis_demo/ 是根據 application.properties 配置中的 server.portserver.servlet.context-path 決定
  • 靜態文件,即 static 路徑下的文件,可以直接通過http://localhost:8080/springboot_mybatis_demo/xxx 訪問

然后運行項目,在瀏覽器中輸入上面的地址就能訪問

配置 Mybatis Generator 自動生成 Model 實體

pom.xml 添加依賴項和插件

<!-- mybatis-generator -->
<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.3.7</version>
</dependency>
<!-- mybatis generator 自動生成代碼插件 -->
<plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.3.7</version>
    <configuration>
        <configurationFile>src/main/resources/Generator/GeneratorConfig.xml</configurationFile>
        <overwrite>true</overwrite>
        <verbose>true</verbose>
    </configuration>
</plugin>

resources/Generator 目錄下新建 GeneratorConfig.xml 文件
這個配置文件中涉及到路徑的節點都可以改

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <!--mysql 連接數據庫jar 這里選擇自己本地位置-->
    <classPathEntry location="E:\Maven\Repository\mysql\mysql-connector-java\8.0.23\mysql-connector-java-8.0.23.jar" />
    <context id="default" targetRuntime="MyBatis3">

        <commentGenerator>
            <!-- 是否去除自動生成的注釋 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>

        <!--數據庫連接的信息:驅動類、連接地址、用戶名、密碼 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8&amp;useSSL=false&amp;nullCatalogMeansCurrent=true"
                        userId="root"
                        password="123456">
        </jdbcConnection>

        <!-- 默認false,把JDBC DECIMAL 和 NUMERIC 類型解析為 Integer,為 true時把JDBC DECIMAL 和
           NUMERIC 類型解析為java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- targetProject:生成PO類的位置 -->
        <javaModelGenerator targetPackage="com.springboot_mybatis_demo.Models"
                            targetProject="src/main/java">
            <!-- enableSubPackages:是否讓schema作為包的后綴 -->
            <property name="enableSubPackages" value="false" />
            <!-- 從數據庫返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!-- targetProject:mapper映射文件生成的位置
           如果maven工程只是單獨的一個工程,targetProject="src/main/java"
           若果maven工程是分模塊的工程,targetProject="所屬模塊的名稱",例如:
           targetProject="ecps-manager-mapper",下同-->
        <sqlMapGenerator targetPackage="com.springboot_mybatis_demo.Mappers"
                         targetProject="src/main/java">
            <!-- enableSubPackages:是否讓schema作為包的后綴 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>

        <!-- targetPackage:mapper接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.springboot_mybatis_demo.DAO"
                             targetProject="src/main/java">
            <!-- enableSubPackages:是否讓schema作為包的后綴 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>

        <!-- 指定數據庫表 -->
        <table schema="" tableName="users" domainObjectName="UserEntity"></table>
    </context>
</generatorConfiguration>

還有一個坑

機翻:

MySql不支持SQL目錄和模式。如果在MySql中運行createschema命令,它實際上會創建一個數據庫,而JDBC驅動程序會將其報告為一個目錄。但是MySql語法不支持標准的catalog..table SQL語法。
因此,最好不要在生成器配置中指定目錄或模式。只需在JDBC URL中指定表名和數據庫。
如果您使用的是8.x版的Connector/J,您可能會注意到生成器試圖為MySql信息模式(sys、information_schema、performance_schema等)中的表生成代碼,這可能不是您想要的!要禁用此行為,請將屬性“nullCatalogMeansCurrent=true”添加到JDBC URL。

雙擊插件生成實體類

實體類 UserEntity

public class UserEntity
{
    private Integer id;

    private String username;

    private String password;

    public Integer getId()
    {
        return id;
    }

    public void setId(Integer id)
    {
        this.id = id;
    }

    public String getUsername()
    {
        return username;
    }

    public void setUsername(String username)
    {
        this.username = username == null ? null : username.trim();
    }

    public String getPassword()
    {
        return password;
    }

    public void setPassword(String password)
    {
        this.password = password == null ? null : password.trim();
    }
}

DAO 和 Mapper

其實這里的DAO和Mapper是一樣的
MyBatis支持2種類型的映射器:XML映射器和接口映射器,在這里以定義並使用接口映射器為例
自動生成的 Mapper 可能不會加 @Mapper 注解,要注意

UserEntityMapper

@Mapper
public interface UserEntityMapper
{
    long countByExample(UserEntityExample example);

    int deleteByExample(UserEntityExample example);

    int deleteByPrimaryKey(Integer id);

    int insert(UserEntity record);

    int insertSelective(UserEntity record);

    List<UserEntity> selectByExample(UserEntityExample example);

    UserEntity selectByPrimaryKey(Integer id);

    int updateByExampleSelective(@Param("record") UserEntity record, @Param("example") UserEntityExample example);

    int updateByExample(@Param("record") UserEntity record, @Param("example") UserEntityExample example);

    int updateByPrimaryKeySelective(UserEntity record);

    int updateByPrimaryKey(UserEntity record);

    @Insert("insert into users(username, password) values(#{username,jdbcType=VARCHAR},#{password,jdbcType=VARCHAR})")
    void Save(@Param("username") String username, @Param("password") String password);

    @Select("select * from users where username=#{username}")
    UserEntity GetUserByUsername(@Param("username") String username);

    @Select("select * from users where username=#{username} and password=#{password}")
    UserEntity GetUserByUsernameAndPassowrd(@Param("username") String username, @Param("password") String password);

}

Service

UserService ,這里的 @Autowired可能會標紅,可以不管

@Service
public class UserService
{
    @Autowired
    private UserEntityMapper _userEntityMapper;

    public UserEntity GetUserByUsername(String username)
    {
        return this._userEntityMapper.GetUserByUsername(username);
    }

    public UserEntity GetUserByUsernameAndPassword(String username, String password)
    {
        return this._userEntityMapper.GetUserByUsernameAndPassowrd(username, password);
    }

    public void Save(UserEntity userEntity)
    {
        this._userEntityMapper.Save(userEntity.getUsername(), userEntity.getPassword());
    }
}

Controller

UserController,這里的控制器使用了兩種獲取值的方式分別是 th:objectname

@RestController
@RequestMapping("/UserController")
public class UserController
{
    @Autowired
    private UserService _userService;

    @RequestMapping("/")
    public ModelAndView Index(Model model)
    {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("User/Index");
        //初始化Index頁面需要的變量
        model.addAttribute("userEntity", new UserEntity());
        model.addAttribute("LoginMessage", "");

        return mav;
    }

    @RequestMapping(value = "/Login/DoLogin", method = RequestMethod.POST)
    public ModelAndView DoLogin(@ModelAttribute UserEntity userEntity, Model model, @RequestParam(name = "btn") String btn)
    {
        ModelAndView mav = new ModelAndView();
        model.addAttribute("userEntity", new UserEntity());
        model.addAttribute("LoginMessage", "");

        //先確定點擊的按鈕
        if (true == btn.equals("Register"))
        {
            mav.setViewName("User/Register");
        }
        else
        {
            String username = userEntity.getUsername();
            String password = userEntity.getPassword();
            if (username.equals("") || password.equals(""))
            {
                model.addAttribute("LoginMessage", "用戶名或密碼不能為空");
                mav.setViewName("User/Index");
            }
            else
            {
                UserEntity user = this._userService.GetUserByUsernameAndPassword(username, password);
                if (user == null)
                {
                    model.addAttribute("LoginMessage", "用戶名或密碼錯誤");
                    mav.setViewName("User/Index");
                }
                else
                {
                    mav.setViewName("User/Success");
                }
            }
        }

        return mav;
    }

    //初始化注冊頁面
    @RequestMapping("/User/Register")
    public ModelAndView Register(Model model)
    {
        model.addAttribute("username", "");
        model.addAttribute("RegisterMessage", "");
        ModelAndView mav = new ModelAndView();
        mav.setViewName("User/Register");
        return mav;
    }

    //注冊操作
    @RequestMapping(value = "/Register/DoRegister", method = RequestMethod.POST)
    public ModelAndView DoRegister(Model model, @RequestParam(name = "username") String username, @RequestParam(name = "password") String password, @RequestParam(name = "repeatPassword") String repeatPassword)
    {
        ModelAndView mav = new ModelAndView();
        if (username.equals("") || password.equals("") || repeatPassword.equals(""))
        {
            model.addAttribute("RegisterMessage", "用戶名、密碼或重復密碼不能為空");
            mav.setViewName("User/Register");
        }
        else
        {
            if (false == password.equals(repeatPassword))
            {
                model.addAttribute("RegisterMessage", "兩次密碼不一致");
                model.addAttribute("username", username);
                mav.setViewName("User/Register");
            }
            else if (null != this._userService.GetUserByUsername(username))
            {
                model.addAttribute("RegisterMessage", "用戶已存在");
                mav.setViewName("User/Register");
            }
            else
            {
                UserEntity user = new UserEntity();
                user.setUsername(username);
                user.setPassword(password);
                this._userService.Save(user);
                model.addAttribute("userEntity", new UserEntity());
                model.addAttribute("LoginMessage", "");
                mav.setViewName("User/Index");
            }
        }

        return mav;
    }
}

html 頁面

Index.html,登錄和注冊使用的是不同的傳值方法,登錄使用的是 th:object ,注冊用的是從標簽的 name 屬性取值, th:value 只用於顯示后端傳到前端的值,可以不用

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <link href="http://localhost:8080/springboot_mybatis_demo/css/MyStyleSheet.css" type="text/css" rel="stylesheet">
    <title>User Index</title>
</head>
<body>
<h1>This is User Index View</h1>
<form action="#" th:action="@{/UserController/Login/DoLogin}" th:object="${userEntity}" method="post">
    <label>用戶名:
        <input type="text" th:field="*{username}"/>
    </label>
    <br>
    <label>密碼:
        <input type="password" th:field="*{password}"/>
    </label>
    <br>
    <label style="color: red" th:text="${LoginMessage}" th:if="${not #strings.isEmpty(LoginMessage)}">

    </label>
    <br>
    <label>
        <button type="submit" name="btn" value="Login">登錄</button>
    </label>
    <button type="submit" name="btn" value="Register">注冊</button>
</form>
</body>
</html>

Success.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link href="http://localhost:8080/springboot_mybatis_demo/css/MyStyleSheet.css" type="text/css" rel="stylesheet">
    <title>Success Page</title>
</head>
<body>
<h1>Login Success</h1>
</body>
</html>

Register.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <link href="http://localhost:8080/springboot_mybatis_demo/css/MyStyleSheet.css" type="text/css" rel="stylesheet">
    <title>Register Page</title>
</head>
<body>
<h1>This is Register Page</h1>
<form action="#" th:action="@{/UserController/Register/DoRegister}" method="post">
<label>用戶名:
    <input type="text" name="username" th:value="${username}"/>
</label>
<br>
<label>密碼:
    <input type="password" name="password" />
</label>
<br>
<label>重復密碼:
    <input type="password" name="repeatPassword"/>
</label>
<br>
<label style="color: red" th:text="${RegisterMessage}" th:if="${not #strings.isEmpty(RegisterMessage)}">

</label>
<br>
<label>
    <input type="submit" value="注冊"/>
</label>
</form>
</body>
</html>

完整項目結構

完整 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.4.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com</groupId>
    <artifactId>springboot_mybatis_demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot_mybatis_demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <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.1.4</version>
        </dependency>

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

        <!-- mybatis-generator -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.7</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <!-- mybatis generator 自動生成代碼插件 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.7</version>
                <configuration>
                    <configurationFile>src/main/resources/Generator/GeneratorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

因為控制器的返回值是視圖,所以要這樣訪問,根據控制器的標注修改 url ,如果只是 html + js 的話,可以直接 Views/ 訪問視圖

Spring Boot + Mybatis 項目搭建和登錄注冊例子 結束


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM