如何利用IDEA搭建SpringBoot项目整合mybatis实现简单的登录功能
利用闲余时间想自己搭建一个springboot+mybatis的项目,提升一下自己对项目的了解,毕竟自己还是一个小白,在这里为自己创建项目的过程做一个记录,以便以后回忆。同时将搭建中遇到的问题也在这里做记录。如有遇到同样问题的同学,希望能给你一下借鉴。
springboot的优势之一就是快速搭建项目,省去了自己导入jar包和配置xml的时间,使用非常方便。
一,搭建项目:
1、打开idea,点击file→new→project...,如图1所示
图1 搭建项目
2、当我们选择project...后,会看见如图2所示的页面,选择spring initializr,点击next即可。
图2 搭建项目
3、接下来将看到如图3所示的页面,在这个页面中我只是修改了名称。然后点击next进行下一步。
图3 搭建项目
4、当我点击next时,却出现如图4所示的错误,这由于创建时因为artifact的命名为大小写混合,将大写改为小写即可正常创建。
图4 搭建项目 (注意名称大小写问题)
5、接下来我们修改上面的错误,我将springboottest1→springboottest1,然后进行下一步。会看见如图5所示的页面。 在当前页面中我们一次选择左侧的web、template engines、sql。然后在中间部分选择我们需要的选项,最终选择结果如最右侧所示。然后点击next,进行下一步。
图5 搭建项目(选择需要的内容)
6、如图6所示,进人创建项目的最后一个页面,在这里我们可以修改项目保存的位置。确认自己输入的内容,点击fiish即可完成项目的创建。
图6 搭建项目(可以修改文件路径)
7、点击finish后,出现如图7所示页面,我们选择new window即可,即在新的idea中打开我们新建的项目。
图7 打开项目
二、启动项目、添加配置文件等
1、打开新项目后,我们可以观察一下左侧的项目结构。如图8所示。
生成的项目中,resources文件夹下,static文件夹下存放静态文件,比如css、js、html和图片等 。
templates下存放html文件,controller默认访问该文件夹下的html文件。
这个在application.properties配置文件中是可以修改的。
下面为项目生成的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>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>
图8 项目文件结构
2、了解项目的文件结构后,我们尝试着启动项目。我们发现项目启动过程中出现错误,错误信息如图9所示。
图9 项目启动报错
这是因为我们创建spring boot项目时,在选择组件时添加了mysql、mybatis,但现在还没有配置数据库,导致项目启动报错。
我们需要在项目的application.properties文件中配置数据信息。如图10所示,是我自己配置的数据库,具体情况根据自己数据库的设置配置。
图10 数据库配置
数据库采用mysql数据库,下面是数据库的设计,只有几个简单的字段。如图11所示。
图11 数据库设计
这里也可以不使用application.properties文件,采用更加简洁的application.yml文件。将resource文件夹下原有的application.properties文件删除,创建application.yml配置文件(备注:其实springboot底层会把application.yml文件解析为application.properties), 文件的内容如下(此处只配置最基本的):
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
接下来再次尝试重新启动项目。发现项目可以正常启动了。可以打开浏览器访问http://localhost:8080/,访问结果如图12所示。证明项目正常启动了。
图12 访问结果
三、项目整合mybatis
1、在application.yml文件中添加mybatis。
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、在pom.xml中添加 mybatis generator 自动生成代码插件。
<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、在resource文件夹下创建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> <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包--> <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、所有文件创建完成后,还需要进行简单的配置。run→edit configurations...,然后选择maven,配置command line。
5、所用文件创建完成,并配置好相关设置,重新启动项目,启动后运行generator。通过控制台可以看见代码是否生成成功,或失败的原因。如果代码生成成功,可以在项目文件夹中看见生成的项目。
这个过程共生成三个文件,一个实体类,dao,还有sql语句。
5.1、生成的实体类entity:
5.2、生
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; } }
成的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、生成的sql语句(其中一些没有用的注释被我删掉了):
<?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>
四、测试访问
做好以上的准备以后,可以简单的写一个小页面,试着访问一下。
同时这个时候可以自己了解一下@controller与@restcontroller的区别,以及@responsebody的用法。
1、比如写一个简单的html页面,helloword.html。
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>helloword</title> </head> <body> <h1>hello springboot!!!</h1> </body> </html>
2、访问页面的controller。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、重新启动项目,访问,访问的结果如下所示。
五、编写用户登录过程代码
1、编写简单的登录页面与注册页面
(1)登录页面 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> 密 码:<input type="password" name="password" /><br> <input type="submit" value="登录" /> <a href="/user/registerpage" target="_blank">注册</a> </form> </body> </html>
页面效果:
(2)注册页面 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>
页面效果:
(3)登录成功页面 index.html
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>登录成功</title> </head> <body> <h1>用户名与密码正确,登录成功!!!</h1> </body> </html>
页面效果:
(4)登录失败页面 loginerror.html
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>登录失败</title> </head> <body> <h1>用户名或密码错误,登录失败!!!</h1> </body> </html>
页面效果:
2、对于写代码的顺序,我是从xml(sql语句)开始写,然后dao,service,最后写controller。下面为我的部分代码。(开始生成的代码没有用到的部分被我删除掉了)
(1)xml(sql语句) 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层 usermapper.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)servicr层 userloginservice.java
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层 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 "注册成功!"; } } } }
由于有同学问我要源码,有时候我可能看不见消息,所以将源码在百度云中分享出来,大家根据自己需要,自行下载吧,如果有什么建议就评论吧:
链接: https://pan.baidu.com/s/1to00d-ehnwa8tm6vhrgiba
提取码: waeu
总结
到此这篇关于如何利用idea搭建springboot项目整合mybatis实现简单的登录功能的文章就介绍到这了,更多相关idea搭建springboot项目整合mybatis实现登录内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!