IDEA+springboot+thymeleaf+mysql的简单登录

上一篇 拦截器(Interceptor)和过滤器(Filter)

IDEA+springboot+thymeleaf+mysql的世上最简单登录

#一、前期准备
1.下载安装好开发需要的环境跟软件mysql跟IDEA,具体怎么安装可以上网搜索,IDEA配置好本地maven仓库跟sdk。
2.在mysql中创建一个数据库并且创建一个user的表填入数据如下图所示
3.在建立springboot项目时候读者要熟悉springmvc的xml配置基本构建,否则很多maven导包等一些配置会很蒙的,这里适合在熟悉springmvc构建的基础上讲解操作。
在这里插入图片描述

二、创建springboot项目

1、打开IDEA,点击File→New→Project…,如下图所示
2、完成一个就一直往下next到finish 在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
3、建立成功后如下图所示
在这里插入图片描述
4.自动生成的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.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</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.1.1</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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

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

</project>

4.启动项目
这里必须先在properties配置好数据库连接再启动项目否者会引找不到数据库连接报错
application.properties添加配置如下

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=luchan06

在这里插入图片描述
启动成功console
在这里插入图片描述
5.浏览器 输入127.0.0.1:8080 出现如下图所示代码最基本的springboot框架完好。
在这里插入图片描述
6.由于springboot没有指定默认首页所以报上面错误,因此这里需要建立一个类设置好addViewControllers函数指定首页如下图所示
在这里插入图片描述
WebMvcConfig类代码

package com.example.demo.common;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
    public class WebMvcConfig extends WebMvcConfigurerAdapter {
    
    
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
    
    

        registry.addViewController("/").setViewName("index.html");

        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        super.addViewControllers(registry);
    }
    }

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form th:action="@{/user/login}" method="post" style="align:center">
    用户名:<input type="text" name="username" /></br>
    密码:<input type="password" name="password" /></br>
    <input type="submit" value="登录">
</form>

</body>
<spricpt>

</spricpt>
</html>

在这里插入图片描述
在这里插入图片描述
6.重启项目,输入127.0.0.1:8080直接进入index.html页面
在这里插入图片描述
7.这里很多人会问为啥一般的springmvc访问有项目名称的,springboot怎么不需要的?怎么配置呢?springboot会默认无需指定项目名称如需要这可以在application.properties中配置如下一句

server.servlet.context-path=/demo

8.重启项目输入127.0.0.1:8080/demo
也可以指定端口N多操作自己可以动手查查springboot的properties的常用配置
在这里插入图片描述

三、配置springmvc实现关联数据库查询

上面都是前端的基础访问,那这里就开始设置怎么进行访问数据库,springboot只是简化springmvc的xml配置因此java项目的包配置啥的都跟springmvc一模一样。
这里介绍如何通过generator逆向工程生成model跟dao跟mapper文件省去手动设置。
1.在pom.xml中添加mybatis-generator-maven-plugin插件注意存放位置在插件标签中

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

2.建立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>
    <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
    <classPathEntry  location="D:\code\SpringMVC\WebContent\WEB-INF\lib\mysql-connector-java-5.1.20.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="luchan06">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成(实体)模型的包名和位置-->
        <javaModelGenerator targetPackage="com.example.demo.entity" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 生成XML映射文件的包名和位置-->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!-- 生成DAO接口的包名和位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.demo.mapper" targetProject="src/main/java">
            <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>


3.点击左边的maven-》Plugins->mybatis-generator->双击mybatis-generator:generate
在这里插入图片描述
在这里插入图片描述
userMapper.java

package com.example.demo.mapper;

import com.example.demo.entity.user;

public interface userMapper {
    
    
 }

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.demo.mapper.userMapper" >
  <resultMap id="BaseResultMap" type="com.example.demo.entity.user" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <result column="sex" property="sex" jdbcType="VARCHAR" />
    <result column="grade" property="grade" jdbcType="INTEGER" />
    <result column="scno" property="scno" jdbcType="INTEGER" />
    <result column="sno" property="sno" jdbcType="INTEGER" />
  </resultMap>
  
</mapper>

user.java

package com.example.demo.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.name
     *
     * @mbggenerated
     */
    private String name;

    /**
     * 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.sex
     *
     * @mbggenerated
     */
    private String sex;

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

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

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

    /**
     * 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.name
     *
     * @return the value of user.name
     *
     * @mbggenerated
     */
    public String getName() {
    
    
        return name;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column user.name
     *
     * @param name the value for user.name
     *
     * @mbggenerated
     */
    public void setName(String name) {
    
    
        this.name = name == null ? null : name.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.sex
     *
     * @return the value of user.sex
     *
     * @mbggenerated
     */
    public String getSex() {
    
    
        return sex;
    }

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

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

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

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

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

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

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

这里我将逆向工程去掉
4.手动建立controller,service,serviceimpl等包文件
在这里插入图片描述
5.创建一个方法进行登录
springboot框架已经自动注入了springmvc注解所以直接使用无需配置相关的springmvc注解的xml
controller.java

package com.example.demo.controller;


import com.example.demo.entity.user;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    
    
    @Autowired
     private UserService userService;

    @RequestMapping("/login")
    public String loginout(HttpServletRequest req, user user)
    {
    
    
        user userLogin= userService.find(user);
        req.setAttribute("userList",userLogin);
        return "login";
    }
}

userService.java

package com.example.demo.service;





import com.example.demo.entity.user;

import java.util.List;

public interface UserService {
    
    
    public  user find(user user);
}

userseriveImpl.java

package com.example.test.service.impl;


import com.example.test.common.BaseService;
import com.example.test.entity.user;
import com.example.test.mapper.userMapper;
import com.example.test.service.UserService;
import org.apache.catalina.mbeans.UserMBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 *
 * @author winnielu
 * @Description
 * @Date  2019年10月12日
 */
@Service
public class UserServiceImpl extends BaseService<user> implements UserService {
    
    
    @Autowired
   private userMapper userMapper;
    public List<user> getAllUser(){
    
    
       return userMapper.getAllUser();
    }
}

usermapper.java

package com.example.test.mapper;

import com.example.test.entity.user;
import com.example.test.until.MyMapper;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;

import java.util.List;

@Mapper
@Component
public interface userMapper extends MyMapper<user> {
    
    
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated
     */
    public List<user> getAllUser();

}

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.demo.mapper.userMapper" >
  <resultMap id="BaseResultMap" type="com.example.demo.entity.user" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <result column="sex" property="sex" jdbcType="VARCHAR" />
    <result column="grade" property="grade" jdbcType="INTEGER" />
    <result column="scno" property="scno" jdbcType="INTEGER" />
    <result column="sno" property="sno" jdbcType="INTEGER" />
  </resultMap>
  <select id="find"  parameterType="com.example.demo.entity.user" resultMap="BaseResultMap">
        SELECT * FROM user where 1=1
    <if test="name != null" >
      and name = #{
    
    name,jdbcType=VARCHAR}
    </if>
    <if test="password != null" >
      and password = #{
    
    password,jdbcType=VARCHAR}
    </if>

    </select>
</mapper>

login.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
欢迎您:<span th:text="${userList.name}">nite</span>


<spricpt>

</spricpt>
</body>
</html>

6.启动项目
在这里插入图片描述
报错由于没有配置mybatis的映射所以要在properties添加bean跟mapper的映射路径
如下

#mapper跟jopo类路径配置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.demo.entity

启动后会报错
修改pom.xml版本
解决方法:pom.xml的mysql包没有导入版本
添加
mysql
mysql-connector-java
5.1.34
runtime

7.再次启动登录
在这里插入图片描述
由于本人还是个菜鸟,所以制作了个最简单的登录,请谅解
[参考文档]
1.https://blog.csdn.net/weixin_42685022/article/details/82215893

猜你喜欢

转载自blog.csdn.net/weixin_40620651/article/details/103051246