Use IDEA to build a SpringBoot project, integrate mybatis, and implement a simple login function.

Use IDEA to build a SpringBoot project, integrate mybatis, and implement a simple login function.


for reference only! ! !

for reference only! ! !

for reference only! ! !


        I want to use my spare time to build a springboot+mybatis project by myself to improve my understanding of the project. After all, I am still a novice, so I will make a record of the process of creating my project here so that I can recall it later. At the same time, the problems encountered in the construction are also recorded here. If you have the same problem, I hope you can learn from it.

       One of the advantages of springboot is that it can quickly build a project, which saves the time of importing the jar package and configuring the xml, and it is very convenient to use.


First, build the project:

1. Open IDEA, click File→New→Project..., as shown in Figure 1

                                                            Figure 1 Building the project


2. When we select project..., we will see the page shown in Figure 2 , select Spring Initializr, and click NEXT.

                                                                                           Figure 2 Building the project


3. Next, you will see the page shown in Figure 3. In this page, I just changed the name. Then click NEXT to proceed to the next step.

                                                                                         Figure 3 Building the project

4. When I click NEXT, the error shown in Figure 4 appears . This is because the name of Artifact is mixed case, and it can be created normally by changing uppercase to lowercase.

                                                                             Figure 4 Building the project (pay attention to the capitalization of the name)

5. Next, we will modify the above error, I will springbootTest1→springboottest1, and then proceed to the next step. You will see the page shown in Figure 5 . In the current page, we select Web, Template Engines, SQL on the left at one time. Then select the options we need in the middle part, and the final selection result is shown on the far right. Then click NEXT to proceed to the next step.

                                                                          Figure 5 Build the project (select the required content)

6. As shown in Figure 6 , enter the last page of creating a project, where we can modify the location where the project is saved. Confirm your input and click Fiish to complete the project creation.

                                                             Figure 6 Building the project (you can modify the file path)

7. After clicking Finish, the page shown in Figure 7 appears . We can select New Window, that is, open our newly created project in the new IDEA.

                                                                        Figure 7 Open the project


Second, start the project, add configuration files, etc.

1. After opening a new project, we can observe the project structure on the left. As shown in Figure 8 .

In the generated project, static files, such as css, js, html, and pictures, are stored in the resources folder and the static folder.

The html files are stored under templates, and the controller accesses the html files in this folder by default.

This can be modified in the application.properties configuration file. 

The following pom.xml file is generated for the project :

<?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>springboottest1</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springboottest1</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.4.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>
		<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>1.3.2</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>

                                                                                      Figure 8 Project file structure


2. After understanding the file structure of the project, we try to start the project. We found that an error occurred during the project startup, and the error message is shown in Figure 9 .

                                                                                         Figure 9 Project startup error

This is because when we created the Spring Boot project, mysql and mybatis       were added when selecting components , but the database has not been configured yet, resulting in an error when the project starts.

      We need to configure the data information in the application.properties file of the project. As shown in Figure 10 , it is a database configured by myself, and the specific situation is configured according to the settings of my own database.

                                                                            Figure 10 Database configuration

       The database uses MySQL database, the following is the design of the database, only a few simple fields. As shown in Figure 11 .

                                                                            Figure 11 Database Design

     You can also use a more concise application.yml file instead of the application.properties file here . Delete the original application.properties file in the resource folder , and create an application.yml configuration file (Note: In fact, SpringBoot will parse the application.yml file into application.properties at the bottom ), the content of the file is as follows (only the most basic configuration is here) of):

server:
  port: 8080

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

       Next try restarting the project again. It is found that the project can be started normally. You can open a browser to visit http://localhost:8080/ , and the access result is shown in Figure 12 . Prove that the project started normally.

                                                                                        Figure 12 Access results


3. Project integration mybatis

1. Add mybatis to the application.yml file.


server:
  port: 8080

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

mybatis:
  mapper-locations: classpath:mapper/*.xml  #注意:一定要对应mapper映射xml文件的所在路径
  type-aliases-package: com.example.springboottest1.entity  # 注意:对应实体类的路径

2. Add  mybatis generator to automatically generate code plugins in pom.xml .

<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.1</version>
				<configuration>
					<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
					<overwrite>true</overwrite>
					<verbose>true</verbose>
				</configuration>
			</plugin>
		</plugins>
	</build>

3. Create a generator folder under the resource folder, and create a generatorConfig.xml file in the folder . The contents of the file are as follows:

<?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>
    <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
    <classPathEntry  location="C:\Program Files (x86)\MySQL\Connector.J 5.1\mysql-connector-java-5.1.36-bin.jar"/>
    <context id="DB2Tables"  targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="false"/>
        </commentGenerator>
        <!--数据库连接驱动类,URL,用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1/test" userId="root" password="123456">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成(实体)模型的包名和位置-->
        <javaModelGenerator targetPackage="com.example.springboottest1.entity" targetProject="src">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 生成XML映射文件的包名和位置-->
        <sqlMapGenerator targetPackage="resources.mapper" targetProject="src">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!-- 生成DAO接口的包名和位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.springboottest1.mapper" targetProject="src">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
        <table tableName="user" domainObjectName="user" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>

4. After all files are created, a simple configuration is required. Run→Edit Configurations..., then select maven, configure the Command line.

5. The files used are created, and the relevant settings are configured, restart the project, and run the generator after startup. Through the console, you can see whether the code was generated successfully, or why it failed. If the code generation is successful, you can see the generated project in the project folder.

        This process generates a total of three files, an entity class, dao, and sql statements.

5.1. Generated entity class entity:

package com.example.springboottest1.entity;

public class user {
    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column user.id
     *
     * @mbggenerated
     */
    private Integer id;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column user.username
     *
     * @mbggenerated
     */
    private String username;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column user.password
     *
     * @mbggenerated
     */
    private String password;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column user.age
     *
     * @mbggenerated
     */
    private Integer age;

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column user.id
     *
     * @return the value of user.id
     *
     * @mbggenerated
     */
    public Integer getId() {
        return id;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column user.id
     *
     * @param id the value for user.id
     *
     * @mbggenerated
     */
    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column user.username
     *
     * @return the value of user.username
     *
     * @mbggenerated
     */
    public String getUsername() {
        return username;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column user.username
     *
     * @param username the value for user.username
     *
     * @mbggenerated
     */
    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column user.password
     *
     * @return the value of user.password
     *
     * @mbggenerated
     */
    public String getPassword() {
        return password;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column user.password
     *
     * @param password the value for user.password
     *
     * @mbggenerated
     */
    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column user.age
     *
     * @return the value of user.age
     *
     * @mbggenerated
     */
    public Integer getAge() {
        return age;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column user.age
     *
     * @param age the value for user.age
     *
     * @mbggenerated
     */
    public void setAge(Integer age) {
        this.age = age;
    }
}

5.2. Generated Dao:

package com.example.springboottest1.mapper;

import com.example.springboottest1.entity.user;

public interface userMapper {
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated
     */
    int deleteByPrimaryKey(Integer id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated
     */
    int insert(user record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated
     */
    int insertSelective(user record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated
     */
    user selectByPrimaryKey(Integer id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated
     */
    int updateByPrimaryKeySelective(user record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated
     */
    int updateByPrimaryKey(user record);
}

5.3. The generated SQL statement (some of the useless comments were deleted by me):

<?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.springboottest1.mapper.userMapper" >
  <resultMap id="BaseResultMap" type="com.example.springboottest1.entity.user" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="username" property="username" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <result column="age" property="age" jdbcType="INTEGER" />
  </resultMap>
  <sql id="Base_Column_List" >
      id,
      username,
      password,
      age
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
      select
      <include refid="Base_Column_List" />
      from user
      where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
      delete from user
      where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.example.springboottest1.entity.user" >
      insert into user (id, username, password, age)
      values (
        #{id,jdbcType=INTEGER},
        #{username,jdbcType=VARCHAR},
        #{password,jdbcType=VARCHAR},
        #{age,jdbcType=INTEGER})
  </insert>
  <insert id="insertSelective" parameterType="com.example.springboottest1.entity.user" >
      insert into user
      <trim prefix="(" suffix=")" suffixOverrides="," >
        <if test="id != null" >
          id,
        </if>
        <if test="username != null" >
          username,
        </if>
        <if test="password != null" >
          password,
        </if>
        <if test="age != null" >
          age,
        </if>
      </trim>
      <trim prefix="values (" suffix=")" suffixOverrides="," >
        <if test="id != null" >
          #{id,jdbcType=INTEGER},
        </if>
        <if test="username != null" >
          #{username,jdbcType=VARCHAR},
        </if>
        <if test="password != null" >
          #{password,jdbcType=VARCHAR},
        </if>
        <if test="age != null" >
          #{age,jdbcType=INTEGER},
        </if>
      </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.example.springboottest1.entity.user" >
      update user
      <set >
        <if test="username != null" >
          username = #{username,jdbcType=VARCHAR},
        </if>
        <if test="password != null" >
          password = #{password,jdbcType=VARCHAR},
        </if>
        <if test="age != null" >
          age = #{age,jdbcType=INTEGER},
        </if>
      </set>
      where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.example.springboottest1.entity.user" >
      update user
      set username = #{username,jdbcType=VARCHAR},
        password = #{password,jdbcType=VARCHAR},
        age = #{age,jdbcType=INTEGER}
      where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

4. Test access

After doing the above preparations, you can simply write a small page and try to visit it.

At the same time, you can learn about the difference between @Controller and @RestController , and the usage of @ResponseBody .

1. For example, write a simple HTML page, HelloWord.html .

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>HelloWord</title>
</head>
<body>
<h1>hello springboot!!!</h1>
</body>
</html>

2. Access the controller of the page. helloController.java

package com.example.springboottest1.controller;

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

@Controller
@RequestMapping(value = {"/hello"})
public class helloController {

    @RequestMapping(value = {"/springboot"})
    public String hello(){
        return "HelloWord";
    }
}

3. Restart the project and visit http://localhost:8080/hello/springboot . The result of the visit is as follows.

Five, write user login process code

1. Write a simple login page and registration page

(1) Login page   userLogin.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户登录</title>
</head>
<body>
请输入用户名与密码登录
<form action="/user/userLogin" method="post">
    用户名:<input type="text" name="username" /><br>
    密&nbsp;&nbsp;&nbsp;码:<input type="password" name="password" /><br>
    <input type="submit" value="登录" />
    <a href="/user/registerpage" target="_blank">注册</a>
</form>
</body>
</html>

page effect:

(2) Registration page   register.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
</head>
<body>
<form action="/user/uregister" method="post">
    用户名:<input type="text" name="username" /></br>
    密码:<input type="password" name="password" /></br>
    确认密码:<input type="password" name="password2" /></br>
    年龄:<input type="text" name="age" /></br>
    <input type="submit" value="注册">
</form>
</body>
</html>

page effect:

(3) Login success page   index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录成功</title>
</head>
<body>
<h1>用户名与密码正确,登录成功!!!</h1>

</body>
</html>

page effect:

(4) login error page   loginError.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录失败</title>
</head>
<body>
<h1>用户名或密码错误,登录失败!!!</h1>
</body>
</html>

page effect:

2. For the order of writing code, I start from xml (sql statement), then Dao, Service, and finally Controller. Below is part of my code. (The unused part of the code generated at the beginning was deleted by me)

(1) xml (sql statement)  userMapper.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.springboottest1.mapper.userMapper" >
 
    <!--用户登录验证-->
    <select id="userlogin" parameterType="user" resultType="User">
        SELECT id,username,password,age FROM user WHERE username = #{username} AND password = #{password}
    </select>

    <!--新用户注册  方式1-->
    <insert id="adduser" parameterType="user" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO user (username,password,age) VALUES (#{username},#{password},#{age})
    </insert>

    <!--新用户注册  方式2-->
    <insert id="adduser1" parameterType="user">
        INSERT INTO user (id,username,password,age) VALUES (UUID(),#{username},#{password},#{age})
    </insert>

</mapper>

(2) Dao  layersuserMapper.java

package com.example.springboottest1.mapper;

import com.example.springboottest1.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;

import java.util.Map;

@Mapper
@Component
public interface userMapper {

    //用户登录
    User userlogin(@Param("username") String username,@Param("password") String password);

    //注册新用户(方式1)
    int adduser(@Param("username") String username, @Param("password") String password, @Param("age") int age);

    //注册新用户(方式2)
    int adduser1(@Param("username") String username, @Param("password") String password, @Param("age") int age);
}

(3) UserLoginService.java in the Servicr layer  

package com.example.springboottest1.service;

import com.example.springboottest1.entity.User;
import com.example.springboottest1.mapper.userMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class UserLoginService {

    /**
     * 注入dao
     */
    @Autowired
    private userMapper usermapper;

    //用户登录
    public User userLogin(String username,String password){
        User user = usermapper.userlogin(username,password);
        return user;
    }

    //注册新用户
    public int adduser(String username,String password,int age){


        return usermapper.adduser(username,password,age);
        //return usermapper.adduser1(username,password,age);     //对应sql语句中的第二种注册方式
    }
}

(4) Controller layer   UserLoginController.java

package com.example.springboottest1.controller;

import com.example.springboottest1.entity.User;
import com.example.springboottest1.service.UserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(value = {"/user"})
public class UserLoginController {

    /**
     * 注入service
     */
    @Autowired
    private UserLoginService userLoginService;

    /**
     * 跳转到用户登录页面
     * @return 登录页面
     */
    @RequestMapping(value = {"/loginHtml"})
    public String loginHtml(){
        return "userLogin";
    }

    /**
     * 跳转到用户注册页面
     * @return 注册页面
     */
    @RequestMapping(value = {"/registerpage"})
    public String registerpage(){
        return "register";
    }

    /**
     * 获取用户名与密码,用户登录
     * @return 登录成功页面
     */
    @RequestMapping(value = {"/userLogin"})
    public String userLogin(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletRequest request){

        User user = userLoginService.userLogin(username,password);

        if(user != null){                                                  //登录成功
            request.getSession().setAttribute("session_user",user);     //将用户信息放入session
            return "index";
        }
        return "loginError";
    }

    /**
     * 注册新用户
     * @return 注册结果
     */
    @ResponseBody
    @RequestMapping(value = {"/uregister"})
    public String addUser(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("password2") String password2,
                          @RequestParam("age") int age){

        if(!password.equals(password2)){

            return "两次密码不相同,注册失败!!";
        }else {
            int res = userLoginService.adduser(username,password,age);
            if(res == 0){
                return "注册失败!";
            }else {
                return "注册成功!";
            }
        }

    }
}

If there are mistakes in the text, I hope to point out and make progress together!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324148472&siteId=291194637