spring boot1.1 idea + springboot + mybatis(mybatis-generator) +mysql +html实现简单的登录注册
前言
这两年springboot比较火,而我平时的工作中不怎么使用spring boot,所以工作之余就自己写写项目练练手,也跟大家一起学习。
打算从最开始的搭架子,登录注册,到后台管理的增删改查,业务逻辑,引用权限框架,如果能一直坚持下去就再增加缓存,中间件,消息队列,数据库方面分库分表,负载均衡这些比较主流的东西都玩一遍。
页面基本上都是在网上找的免费模板,也会借鉴一下其他的博客,如果引用较多会挂上原文链接。
spring boot
这里引用一篇阿里云的文章,有兴趣的朋友可以去看一看,是spring boot的介绍和使用。
正文
创建项目,用的jdk版本是1.8,
项目结构
js css这些资源要放在static包下,我放别的地方引用不进去,后文再说。
页面位置
pom文件
<?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>org</groupid> <artifactid>mall</artifactid> <version>0.0.1-snapshot</version> <name>mall</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-web</artifactid> </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> <!-- spring boot mybatis依赖 --> <dependency> <groupid>org.mybatis.spring.boot</groupid> <artifactid>mybatis-spring-boot-starter</artifactid> <version>1.3.2</version> </dependency> <!-- mysql连接驱动依赖 --> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> <version>8.0.11</version> <!-- <version>${mysql-connector}</version>--> </dependency> <!-- spring boot freemarker依赖 --> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-freemarker</artifactid> </dependency> <!-- swagger --> <dependency> <groupid>io.springfox</groupid> <artifactid>springfox-swagger2</artifactid> <version>2.5.0</version> </dependency> <!-- swagger-ui --> <dependency> <groupid>io.springfox</groupid> <artifactid>springfox-swagger-ui</artifactid> <version>2.5.0</version> </dependency> <!-- fastjson --> <dependency> <groupid>com.alibaba</groupid> <artifactid>fastjson</artifactid> <version>1.2.47</version> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-thymeleaf</artifactid> </dependency> <!-- 热部署 --> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-devtools</artifactid> <optional>true</optional> </dependency> <!-- maven方式是使用mybatis-generator--> <!-- mybatis自动生成工具--> <dependency> <groupid>org.mybatis.generator</groupid> <artifactid>mybatis-generator-core</artifactid> <version>1.3.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-maven-plugin</artifactid> <configuration> <fork>true</fork> <!-- spring-boot:run 中文乱码解决 --> <jvmarguments>-dfile.encoding=utf-8</jvmarguments> </configuration> </plugin> <!-- mybatis generator 自动生成代码插件 --> <plugin> <groupid>org.mybatis.generator</groupid> <artifactid>mybatis-generator-maven-plugin</artifactid> <version>1.3.2</version> <configuration> <configurationfile> src/main/resources/generator/generatorconfig.xml </configurationfile> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> <executions> <execution> <id>generate mybatis artifacts</id> <goals> <goal>generate</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
application.properties
换上自己的配置
## 数据源配置 spring.datasource.url=jdbc:mysql://localhost:3306/independenttest?useunicode=true&characterencoding=utf8&servertimezone=utc ## 数据库账号密码 spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.cj.jdbc.driver ##spring.datasource.driver-class-name=com.mysql.jdbc.driver ## 实体类 mybatis.typealiasespackage=com.wjy.entity ## mapper.xml mybatis.mapperlocations=classpath:mapper/*.xml ## freemarker 配置 ## 文件配置路径 spring.freemarker.template-loader-path=classpath:/web/ spring.freemarker.cache=false spring.freemarker.charset=utf-8 spring.freemarker.check-template-location=true spring.freemarker.content-type=text/html spring.freemarker.expose-request-attributes=true spring.freemarker.expose-session-attributes=true ## 获取contextpath spring.freemarker.request-context-attribute=request spring.freemarker.suffix=.ftl
mapper.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.wjy.mapper.tusermapper" > <resultmap id="baseresultmap" type="com.wjy.entity.tuser" > <id column="id" property="id" jdbctype="bigint" /> <result column="username" property="username" jdbctype="varchar" /> <result column="userpassword" property="userpassword" jdbctype="varchar" /> <result column="usertel" property="usertel" jdbctype="varchar" /> <result column="login_error_num" property="loginerrornum" jdbctype="bit" /> <result column="lock_time" property="locktime" jdbctype="integer" /> <result column="status" property="status" jdbctype="bit" /> <result column="real_name" property="realname" jdbctype="varchar" /> <result column="id_card" property="idcard" jdbctype="varchar" /> <result column="userpassword_salt" property="userpasswordsalt" jdbctype="varchar" /> <result column="remark" property="remark" jdbctype="varchar" /> </resultmap> <sql id="base_column_list" > id, username, userpassword, usertel, login_error_num, lock_time, status, real_name, id_card, userpassword_salt, remark </sql> <select id="selectbyprimarykey" resultmap="baseresultmap" parametertype="java.lang.long" > select <include refid="base_column_list" /> from t_user where id = #{id,jdbctype=bigint} </select> <select id="selectbyname" resultmap="baseresultmap" parametertype="java.lang.string" > select <include refid="base_column_list" /> from t_user where username = #{username,jdbctype=varchar} </select> <delete id="deletebyprimarykey" parametertype="java.lang.long" > delete from t_user where id = #{id,jdbctype=bigint} </delete> <insert id="insert" parametertype="com.wjy.entity.tuser" > insert into t_user (id, username, userpassword, usertel, login_error_num, lock_time, status, real_name, id_card, userpassword_salt, remark) values (#{id,jdbctype=bigint}, #{username,jdbctype=varchar}, #{userpassword,jdbctype=varchar}, #{usertel,jdbctype=varchar}, #{loginerrornum,jdbctype=bit}, #{locktime,jdbctype=integer}, #{status,jdbctype=bit}, #{realname,jdbctype=varchar}, #{idcard,jdbctype=varchar}, #{userpasswordsalt,jdbctype=varchar}, #{remark,jdbctype=varchar}) </insert> <insert id="insertselective" parametertype="com.wjy.entity.tuser" > insert into t_user <trim prefix="(" suffix=")" suffixoverrides="," > <if test="id != null" > id, </if> <if test="username != null" > username, </if> <if test="userpassword != null" > userpassword, </if> <if test="usertel != null" > usertel, </if> <if test="loginerrornum != null" > login_error_num, </if> <if test="locktime != null" > lock_time, </if> <if test="status != null" > status, </if> <if test="realname != null" > real_name, </if> <if test="idcard != null" > id_card, </if> <if test="userpasswordsalt != null" > userpassword_salt, </if> <if test="remark != null" > remark, </if> </trim> <trim prefix="values (" suffix=")" suffixoverrides="," > <if test="id != null" > #{id,jdbctype=bigint}, </if> <if test="username != null" > #{username,jdbctype=varchar}, </if> <if test="userpassword != null" > #{userpassword,jdbctype=varchar}, </if> <if test="usertel != null" > #{usertel,jdbctype=varchar}, </if> <if test="loginerrornum != null" > #{loginerrornum,jdbctype=bit}, </if> <if test="locktime != null" > #{locktime,jdbctype=integer}, </if> <if test="status != null" > #{status,jdbctype=bit}, </if> <if test="realname != null" > #{realname,jdbctype=varchar}, </if> <if test="idcard != null" > #{idcard,jdbctype=varchar}, </if> <if test="userpasswordsalt != null" > #{userpasswordsalt,jdbctype=varchar}, </if> <if test="remark != null" > #{remark,jdbctype=varchar}, </if> </trim> </insert> <update id="updatebyprimarykeyselective" parametertype="com.wjy.entity.tuser" > update t_user <set > <if test="username != null" > username = #{username,jdbctype=varchar}, </if> <if test="userpassword != null" > userpassword = #{userpassword,jdbctype=varchar}, </if> <if test="usertel != null" > usertel = #{usertel,jdbctype=varchar}, </if> <if test="loginerrornum != null" > login_error_num = #{loginerrornum,jdbctype=bit}, </if> <if test="locktime != null" > lock_time = #{locktime,jdbctype=integer}, </if> <if test="status != null" > status = #{status,jdbctype=bit}, </if> <if test="realname != null" > real_name = #{realname,jdbctype=varchar}, </if> <if test="idcard != null" > id_card = #{idcard,jdbctype=varchar}, </if> <if test="userpasswordsalt != null" > userpassword_salt = #{userpasswordsalt,jdbctype=varchar}, </if> <if test="remark != null" > remark = #{remark,jdbctype=varchar}, </if> </set> where id = #{id,jdbctype=bigint} </update> <update id="updatebyprimarykey" parametertype="com.wjy.entity.tuser" > update t_user set username = #{username,jdbctype=varchar}, userpassword = #{userpassword,jdbctype=varchar}, usertel = #{usertel,jdbctype=varchar}, login_error_num = #{loginerrornum,jdbctype=bit}, lock_time = #{locktime,jdbctype=integer}, status = #{status,jdbctype=bit}, real_name = #{realname,jdbctype=varchar}, id_card = #{idcard,jdbctype=varchar}, userpassword_salt = #{userpasswordsalt,jdbctype=varchar}, remark = #{remark,jdbctype=varchar} where id = #{id,jdbctype=bigint} </update> </mapper>
mapper接口
package com.wjy.mapper; import com.wjy.entity.tuser; import java.util.list; public interface tusermapper { int deletebyprimarykey(long id); int insert(tuser record); int insertselective(tuser record); tuser selectbyprimarykey(long id); int updatebyprimarykeyselective(tuser record); int updatebyprimarykey(tuser record); list<tuser> selectbyname(string username); }
service接口
package com.wjy.service; import com.wjy.entity.tuser; import java.util.list; /** *用户service */ public interface tuserservice { //根据用户名查user list<tuser> findtuserbyusername(string username); //根据用户名查user int inserttuser(tuser tuser); }
service实现类
package com.wjy.service.impl; import com.wjy.entity.tuser; import com.wjy.mapper.tusermapper; import com.wjy.service.tuserservice; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.service; import java.util.list; @service public class tuserserviceimpl implements tuserservice { @autowired(required = false) private tusermapper tusermapper; @override public list<tuser> findtuserbyusername(string username) { return tusermapper.selectbyname(username); } @override public int inserttuser(tuser tuser) { return tusermapper.insert(tuser); } }
实体类
package com.wjy.entity; public class tuser { private long id; private string username; private string userpassword; private string usertel; private boolean loginerrornum; private integer locktime; private boolean status; private string realname; private string idcard; private string userpasswordsalt; private string remark; public long getid() { return id; } public void setid(long id) { this.id = id; } public string getusername() { return username; } public void setusername(string username) { this.username = username == null ? null : username.trim(); } public string getuserpassword() { return userpassword; } public void setuserpassword(string userpassword) { this.userpassword = userpassword == null ? null : userpassword.trim(); } public string getusertel() { return usertel; } public void setusertel(string usertel) { this.usertel = usertel == null ? null : usertel.trim(); } public boolean getloginerrornum() { return loginerrornum; } public void setloginerrornum(boolean loginerrornum) { this.loginerrornum = loginerrornum; } public integer getlocktime() { return locktime; } public void setlocktime(integer locktime) { this.locktime = locktime; } public boolean getstatus() { return status; } public void setstatus(boolean status) { this.status = status; } public string getrealname() { return realname; } public void setrealname(string realname) { this.realname = realname == null ? null : realname.trim(); } public string getidcard() { return idcard; } public void setidcard(string idcard) { this.idcard = idcard == null ? null : idcard.trim(); } public string getuserpasswordsalt() { return userpasswordsalt; } public void setuserpasswordsalt(string userpasswordsalt) { this.userpasswordsalt = userpasswordsalt == null ? null : userpasswordsalt.trim(); } public string getremark() { return remark; } public void setremark(string remark) { this.remark = remark == null ? null : remark.trim(); } }
md5utils
package com.wjy.utils; import java.io.unsupportedencodingexception; import java.security.messagedigest; import java.security.nosuchalgorithmexception; public class md5utils { public static string encrypt(string password) { string passwordmd5 = null; try { messagedigest md5 = messagedigest.getinstance("md5"); byte[] bytes = md5.digest(password.getbytes("utf-8")); passwordmd5 = tohex(bytes); } catch (nosuchalgorithmexception | unsupportedencodingexception e) { e.printstacktrace(); } return passwordmd5; } private static string tohex(byte[] bytes) { final char[] hex_digits = "0123456789abcdef".tochararray(); stringbuilder ret = new stringbuilder(bytes.length * 2); for (int i=0; i<bytes.length; i++) { ret.append(hex_digits[(bytes[i] >> 4) & 0x0f]); ret.append(hex_digits[bytes[i] & 0x0f]); } return ret.tostring(); } }
resultutils(这个resultutils是之前从别人那拿过来的,原链接实在找不到了)
package com.wjy.utils; import com.alibaba.fastjson.json; /* * 结果类 * */ public class resultutils { //返回结果true:成功,false:失败 private boolean success = true; //返回信息 private string msg; //返回结果集 private object result; public void setsuccess(boolean success) { this.success = success; } public string getmsg() { return msg; } public void setmsg(string msg) { this.msg = msg; } public object getresult() { return result; } public void setresult(object result) { this.result = result; } public resultutils() { } public resultutils(boolean success, string msg) { this.success = success; this.msg = msg; } public resultutils(boolean success, string msg, object result) { this.success = success; this.msg = msg; this.result = result; } public boolean issuccess() { return success; } /* * 返回成功结果 * */ public object successresult(){ resultutils resultutils = new resultutils(); resultutils.setsuccess(true); resultutils.setmsg("success"); resultutils.setresult(null); return json.tojson(resultutils); } /* * 返回成功结果 * */ public object successresult(object obj){ //判断参数obj是否是string类型 if (obj instanceof string){ return successresult(null, (string) obj); }else{ return successresult(obj, "error"); } } /* * 返回成功结果 * */ public object successresult(object obj, string msg){ resultutils resultutils = new resultutils(); resultutils.setsuccess(true); resultutils.setmsg(msg); resultutils.setresult(obj); return json.tojson(resultutils); } /* * 返回错误结果 * */ public object errorresult(string msg){ resultutils resultutils = new resultutils(); resultutils.setsuccess(false); resultutils.setmsg(msg); resultutils.setresult(null); return json.tojson(resultutils); } /* * 返回错误结果 * */ public object errorresult(object obj){ if (obj instanceof string){ return renderjsonerror(null, (string) obj); }else{ return renderjsonerror(obj, "error"); } } /* * 返回错误结果 * */ public object renderjsonerror(object obj, string msg){ resultutils resultutils = new resultutils(); resultutils.setsuccess(false); resultutils.setmsg(msg); resultutils.setresult(obj); return json.tojson(resultutils); } }
usercontroller
package com.wjy.controller; import com.wjy.entity.tuser; import com.wjy.entity.wmuserusers; import com.wjy.service.tuserservice; import com.wjy.service.wmuserusersservice; import com.wjy.utils.md5utils; import com.wjy.utils.resultutils; import org.springframework.beans.factory.annotation.autowired; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.requestmethod; import org.springframework.web.bind.annotation.restcontroller; import org.thymeleaf.util.stringutils; import javax.servlet.servletexception; import java.io.ioexception; import java.util.list; @restcontroller @requestmapping("/user") public class usercontroller { @autowired private wmuserusersservice wmuserusersservice; @autowired private tuserservice tuserservice; /** * @param * @return * @throws ioexception * @throws servletexception */ @requestmapping(value = "usersignup", method = {requestmethod.get, requestmethod.post}) public object usersignup(tuser tuser) throws ioexception, servletexception { resultutils res = new resultutils(); if (stringutils.isempty(tuser.getusername()) || stringutils.isempty(tuser.getuserpassword())) return res.errorresult("请填写用户名或密码"); list<tuser> tuserlist = tuserservice.findtuserbyusername(tuser.getusername()); if (tuserlist.size() > 0) return res.errorresult("该用户名已经注册过"); tuser.setuserpassword(md5utils.encrypt(tuser.getuserpassword())); int i = tuserservice.inserttuser(tuser); return res.successresult(null, "注册成功!"); } @requestmapping(value = "usersignin", method = {requestmethod.get, requestmethod.post}) public object usersignin(tuser tuser) throws ioexception, servletexception { resultutils res = new resultutils(); if (stringutils.isempty(tuser.getusername()) || stringutils.isempty(tuser.getuserpassword())) return res.errorresult("请填写用户名或密码"); list<tuser> tuserlist = tuserservice.findtuserbyusername(tuser.getusername()); if (tuserlist.size() <= 0) return res.errorresult("未找到账号"); if (tuserlist.size() > 0 && !tuserlist.get(0).getuserpassword().equals(md5utils.encrypt(tuser.getuserpassword()))) return res.errorresult("密码错误"); return res.successresult(null, "登录成功!"); } }
indexcontroller 首页和页面跳转
package com.wjy.controller; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.requestmethod; import org.springframework.web.bind.annotation.restcontroller; import org.springframework.web.servlet.modelandview; import javax.servlet.servletexception; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.io.ioexception; @restcontroller @requestmapping("/") public class indexcontroller { /** * 首页 * @param response * @param request * @return * @throws ioexception * @throws servletexception */ @requestmapping(value ="index",method = {requestmethod.get, requestmethod.post}) public modelandview index(httpservletresponse response, httpservletrequest request) throws ioexception, servletexception { return new modelandview("index"); } /** * html 页面之间的跳转 th:href="@{/topage(url=sign-up2.html)}" * @param request * @return */ @requestmapping(value = "/topage",method = requestmethod.get) public modelandview modelandview(httpservletrequest request){ string url = request.getparameter("url"); return new modelandview(url); } }
generatorconfiguration.xml
mybatis的自动生成工具 放在generator包下
里面的一些配置需要自己修改 然后执行 mvn mybatis-generator:generate命令
<?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="f:\projects\ideaprojects\kfcloud\mysql-connector-java-5.1.25.jar"/> --> <classpathentry location="d:\jar\mysql-connector-java-8.0.11.jar"/> <context id="usergenerator" targetruntime="mybatis3"> <commentgenerator> <property name="suppressdate" value="true"/> <!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressallcomments" value="true"/> </commentgenerator> <!--数据库链接url,用户名、密码 --> <jdbcconnection driverclass="com.mysql.jdbc.driver" connectionurl="jdbc:mysql://127.0.0.1:3306/independenttest?servertimezone=utc" userid="root" password="root"></jdbcconnection> <javatyperesolver> <property name="forcebigdecimals" value="false"/> </javatyperesolver> <!-- 生成模型的包名和位置--> <javamodelgenerator targetpackage="com.wjy.entity" targetproject="src/main/java"> <property name="enablesubpackages" value="true"/> <property name="trimstrings" value="true"/> </javamodelgenerator> <!-- 生成映射文件的包名和位置--> <sqlmapgenerator targetpackage="mapper" targetproject="src/main/resources"> <property name="enablesubpackages" value="true"/> </sqlmapgenerator> <!-- 生成dao的包名和位置--> <javaclientgenerator type="xmlmapper" targetpackage="com.wjy.mapper" targetproject="src/main/java"> <property name="enablesubpackages" value="true"/> </javaclientgenerator> <!-- 要生成的表 tablename是数据库中的表名或视图名 domainobjectname是实体类名--> <table tablename="wm_user_users" domainobjectname="wmuserusers" enablecountbyexample="false" enableupdatebyexample="false" enabledeletebyexample="false" enableselectbyexample="false" selectbyexamplequeryid="false"></table> </context> </generatorconfiguration>
minimalprojectapplication 启动类
package com.wjy; import org.mybatis.spring.annotation.mapperscan; import org.springframework.boot.springapplication; import org.springframework.boot.autoconfigure.springbootapplication; @springbootapplication //mapper接口类扫描包配置 @mapperscan("com.wjy.mapper") public class minimalprojectapplication { public static void main(string[] args) { springapplication.run(minimalprojectapplication.class, args); } }
index.html
<!doctype html> <html lang="zh-cn" xmlns:th="http://www.thymeleaf.org"> <!--[if lt ie 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if ie 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if ie 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt ie 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>minimal and clean sign up / login and forgot form by freehtml5.co</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="free html5 template by freehtml5.co" /> <meta name="keywords" content="free html5, free template, free bootstrap, html5, css3, mobile first, responsive" /> <!-- facebook and twitter integration --> <meta property="og:title" content=""/> <meta property="og:image" content=""/> <meta property="og:url" content=""/> <meta property="og:site_name" content=""/> <meta property="og:description" content=""/> <meta name="twitter:title" content="" /> <meta name="twitter:image" content="" /> <meta name="twitter:url" content="" /> <meta name="twitter:card" content="" /> <!-- place favicon.ico and apple-touch-icon.png in the root directory --> <link rel="shortcut icon" href="favicon.ico"> <link href='https://fonts.googleapis.com/css?family=open+sans:400,700,300' rel='stylesheet' type='text/css'> <link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap.css}"> <link rel="stylesheet" type="text/css" th:href="@{/css/animate.css}"> <link rel="stylesheet" type="text/css" th:href="@{/css/style.css}"> </head> <body class="style-2"> <div class="container"> <div class="row"> <div class="col-md-4"> <!-- start sign in form --> <form id="form" action="#" class="fh5co-form animate-box" data-animate-effect="fadeinleft" > <h2>sign in</h2> <div class="form-group"> <label for="username" class="sr-only">username</label> <input type="text" class="form-control" required="true" id="username" name="username" placeholder="username" autocomplete="off" value="123456"> </div> <div class="form-group"> <label for="userpassword" class="sr-only">password</label> <input type="password" class="form-control" required="true" id="userpassword" placeholder="userpassword" autocomplete="off" value="123456"> </div> <div class="form-group"> <label for="remember"><input type="checkbox" id="remember"> remember me</label> </div> <div class="form-group"> <p>not registered? <a th:href="@{/topage(url=sign-up2.html)}" >sign up</a> | <a th:href="@{/topage(url=forgot2.html)}" >forgot password?</a></p> </div> <div class="form-group"> <input type="" onclick="signin()" value="sign in" class="btn btn-primary"> </div> </form> <!-- end sign in form --> </div> </div> <!--公有js--> <div th:replace="headjs::common_js(~{::script})"> </div> </div> <script th:src="@{/js/index.js}"></script> </body> </html>
index.js
$(function () { //console.info("index.js") }); function signin() { if ($("#form").valid()) { var username = $("#username").val(); var userpassword = $("#userpassword").val(); $.ajax({ url: '/user/usersignin', type: 'get',/*post*/ contenttype: 'application/json', datatype: 'json', data: {username: username, userpassword: userpassword}, success: function (result) { console.info(result.success) confirm(result.msg); //window.location.href = '/topage?url=index_home.html'; } }); } else { return false; } }
sign-up2.html
<!doctype html> <html lang="zh-cn" xmlns:th="http://www.thymeleaf.org"> <!--[if lt ie 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if ie 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if ie 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt ie 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>minimal and clean sign up / login and forgot form by freehtml5.co</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="free html5 template by freehtml5.co"/> <meta name="keywords" content="free html5, free template, free bootstrap, html5, css3, mobile first, responsive"/> <!-- facebook and twitter integration --> <meta property="og:title" content=""/> <meta property="og:image" content=""/> <meta property="og:url" content=""/> <meta property="og:site_name" content=""/> <meta property="og:description" content=""/> <meta name="twitter:title" content=""/> <meta name="twitter:image" content=""/> <meta name="twitter:url" content=""/> <meta name="twitter:card" content=""/> <!-- place favicon.ico and apple-touch-icon.png in the root directory --> <link rel="shortcut icon" href="favicon.ico"> <link href='https://fonts.googleapis.com/css?family=open+sans:400,700,300' rel='stylesheet' type='text/css'> <link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap.css}"> <link rel="stylesheet" type="text/css" th:href="@{/css/animate.css}"> <link rel="stylesheet" type="text/css" th:href="@{/css/style.css}"> <!-- modernizr js --> <script src="js/modernizr-2.6.2.min.js"></script> <!-- for ie9 below --> <!--[if lt ie 9]> <script src="js/respond.min.js"></script> <![endif]--> </head> <body class="style-2"> <div class="container"> <div class="row"> <div class="col-md-4"> <!-- start sign in form --> <form action="#" class="fh5co-form animate-box" data-animate-effect="fadeinleft" id="form"> <h2>sign up</h2> <div class="form-group"> <div class="alert alert-success" role="alert">your info has been saved.</div> </div> <div class="form-group"> <label for="username" class="sr-only">name</label> <input type="text" class="form-control" id="username" name="username" required="true" placeholder="name" autocomplete="off"> </div> <!-- <div class="form-group"> <label for="email" class="sr-only">email</label> <input type="email" class="form-control" id="email" required="true" placeholder="email" autocomplete="off"> </div>--> <div class="form-group"> <label for="userpassword" class="sr-only">password</label> <input type="password" class="form-control" id="userpassword" name="userpassword" minlength="6" maxlength="20" required="true" placeholder="password" autocomplete="off"> </div> <div class="form-group"> <label for="repassword" class="sr-only">re-type password</label> <input type="password" class="form-control" id="repassword" name="repassword" minlength="6" maxlength="20" required="true" placeholder="re-type password" autocomplete="off"> </div> <div class="form-group"> <label for="remember"><input type="checkbox" id="remember"> remember me</label> </div> <div class="form-group"> <p>already registered? <a th:href="@{/topage(url=index.html)}">sign in</a></p> </div> <div class="form-group"> <input type="" value="sign up" onclick="signup()" class="btn btn-primary"> </div> </form> <!-- end sign in form --> </div> </div> <!--公有js--> <div th:replace="headjs::common_js(~{::script})"> </div> </div> </body> <script th:src="@{/js/sign-up2.js}"></script> </html>
sign-up2.js
function signup() { if ($("#form").valid()) { var username = $("#username").val(); var userpassword = $("#userpassword").val(); var repassword = $("#repassword").val(); if ($.trim(userpassword) != $.trim(repassword)) { confirm("两次密码不一致"); return; } $.ajax({ url: '/user/usersignup', type: 'get',/*post*/ contenttype: 'application/json', datatype: 'json', data: {username: username, userpassword: userpassword}, success: function (result) { console.info(result) confirm(result.msg); } }); } else { return false; } }
至于css这些资源就不往上贴了,直接贴源码地址。
链接:https://pan.baidu.com/s/1tm0ecoc9f1nwdrqud3eopw
提取码:d4mg
访问路径 localhost:8080/index
说一下遇到的一些问题
由于第一次使用springboot项目,暂时只会用 thymeleaf 这个东西来使用页面,页面必须要放在templates下,静态资源必须放在static下。
html里要加代码 <html lang="zh-cn" xmlns:th="http://www.thymeleaf.org"> ,
引css: <link rel="stylesheet" type="text/css" th:href="@{/css/style.css}"> ,
引js: <script th:src="@{/js/index.js}"></script>,
而且跳页的时候两个页面之间好像不能互相跳,只能用下面这种方式先请求后台在返回 modelandview,因为在controller中用了 @restcontroller 注解,如果直接return “页面路径” 的话会输出字符串,用重定向好像也没成功,只能用 modelandview 这种方式。
如果有了解别的方法的可以留言,还有就是必须要使用 thymeleaf 这种方式吗,我的页面和静态资源正常来说想放在任何包下都可以吧。
a标签 <a th:href="@{/topage(url=sign-up2.html)}" >
后台方法 (方法名应该改一下,当时没注意)
/** * html 页面之间的跳转 th:href="@{/topage(url=sign-up2.html)}" * @param request * @return */ @requestmapping(value = "/topage",method = requestmethod.get) public modelandview modelandview(httpservletrequest request){ string url = request.getparameter("url"); return new modelandview(url); }
不知道是不是只有这一种方法,有人还知道别的方法的话可以留个言。
在项目中创建了一个公共的html,为了抽取一些公用js,代码如下:
headjs.js
<html lang="zh-cn"> <html lang="zh-cn" xmlns:th="http://www.thymeleaf.org"> <div th:fragment="common_js(scripts)"> <script th:src="@{/js/jquery.min.js}"></script> <!--jquery验证插件 --> <script th:src="@{http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js}"></script> <script th:src="@{/js/bootstrap.min.js}"></script> <script th:src="@{/js/jquery.placeholder.min.js}"></script> <script th:src="@{/js/jquery.waypoints.min.js}"></script> <script th:src="@{/js/main.js}"></script> <!-- modernizr js --> <script th:src="@{/js/modernizr-2.6.2.min.js}"></script> <script th:src="@{/js/respond.min.js}"></script> <!--/* per-page placeholder for additional js */--> <!-- <th:block th:replace="${scripts}" />--> </div> </html>
引入方式
<!--公有js--> <div th:replace="headjs::common_js(~{::script})"> </div>
还有要注意springboot的启动类 minimalprojectapplication 必须要放在项目根目录,
因为spring 在扫描注解的时候是扫描这个文件所在包以下的所有class,
如果其他类放在了高于这个类或其他目录下就会扫描不到。
未完待续
总体来说就是这些,用什么问题和建议随时交流下次会对service和mapper接口做一些抽取,封装baseservice和basedao,再使用一下通用mapper简化一下开发。