Spring MVC+mybatis实现注册登录功能
程序员文章站
2023-11-21 09:16:04
本文实例为大家分享了spring mvc mybatis实现注册登录功能的具体代码,供大家参考,具体内容如下
前期准备:
如下图所示,准备好所需要的包...
本文实例为大家分享了spring mvc mybatis实现注册登录功能的具体代码,供大家参考,具体内容如下
前期准备:
如下图所示,准备好所需要的包
新建工程,导入所需要的包,在web.xml中配置好所需要的,如下
<?xml version="1.0" encoding="utf-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance http://www.springmodules.org/schema/cache/springmodules-cache.xsd http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd" xsi:schemalocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd "> <filter> <filter-name>encoding</filter-name> <filter-class>org.springframework.web.filter.characterencodingfilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> <!-- 前端控制器 --> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> <!-- 在tomcat启动时初始化servlet的优先级,这个数字只能整数,正整数才会初始化servlet --> <load-on-startup>1</load-on-startup> <init-param> <param-name>contextconfiglocation</param-name> <param-value>/web-inf/config/spring.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
配置好如下文件spring.xml
<?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 启用注解 --> <context:annotation-config></context:annotation-config> <!-- 加载注解 --> <context:component-scan base-package="com.register"></context:component-scan> <!-- 导入数据库配置文件 --> <util:properties id="myproperties" location="/web-inf/config/jdbc.properties"> </util:properties> <!-- 创建数据库连接池 --> <bean id="ds" class="com.mchange.v2.c3p0.combopooleddatasource"> <!-- 定义数据库连接的参数 --> <property name="driverclass" value="#{myproperties.driver}"></property> <property name="jdbcurl" value="#{myproperties.url}"></property> <property name="user" value="#{myproperties.username}"></property> <property name="password" value="#{myproperties.password}"></property> <!-- 数据库连接池的两个属性 --> <property name="initialpoolsize" value="3"></property> <property name="maxpoolsize" value="20"></property> </bean> <!-- 替代mybatis的配置文件用来执行mysql语句 --> <bean id="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean"> <property name="datasource" ref="ds" /> <!-- 定义映射文件路径 --> <property name="mapperlocations" value="classpath:com/register/dao/*.xml"></property> </bean> <!-- sqlsession中的bean --> <bean id="sqlsession" class="org.mybatis.spring.sqlsessiontemplate"> <constructor-arg index="0" ref="sqlsessionfactory"></constructor-arg> </bean> <!-- 开启mvc注解 --> <mvc:annotation-driven></mvc:annotation-driven> </beans>
配置好数据库信息
driver=com.mysql.jdbc.driver url=jdbc:mysql://localhost:3306/cheshangbao?useunicode=true&characterencoding=utf8&autoreconnect=true&useoldaliasmetadatabehavior=true username=root password=admin
另外,还有所需要的操作数据库的语句:
<?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"> <!-- sql 映射文件 --> <mapper namespace="com.register.dao"> <!-- 用户注册的判断 --> <insert id="adduser" parametertype="map"> insert into user_login (phone_mobile,login_password,register_time,user_code) values(#{phone_mobile},#{login_password},#{register_time},#{user_code}) </insert> <!-- 用户名唯一性的判断 --> <select id="judgeuser" parametertype="string" resulttype="com.register.vo.user"> select phone_mobile from user_login where phone_mobile=#{phone_mobile} </select> <!-- 用户登录的判断返回一个user给service处理 --> <select id="userlogin" parametertype="map" resulttype="com.register.vo.user"> select phone_mobile,login_password from user_login where phone_mobile=#{phone_mobile} and login_password=#{login_password} </select> </mapper>
前端准备工作
我做的一个简单的注册登录的页面,在页面中对表单进行了第一层的判断,然后在后端又写了第二层验证。
登陆页面如下
<!doctype html public "-//w3c//dtd html 4.01 transitional//en"> <html> <head> <base href="<%=basepath%>"> <title>用户登录</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <link rel="stylesheet" href="assets/css/style.css"> </head> <script type="text/javascript" src="<%=basepath%>/js/jquery-1.8.3.js"></script> <script src="<%=basepath%>/js/my97datepicker/wdatepicker.js" ></script> <script type="text/javascript"> // 用户名合法性的判断 $(function(){ $("#phone_number").blur(function(){ var phone = $("#phone_number").val(); var len = $("#phone_number").val().length; if(len==0||phone==null){ $("#usernameerror").html("手机号不能为空!"); $("#loginfrm").attr("onsubmit","return false"); } }); }); // 密码合法性的判断 $(function(){ $("#pwd").blur(function(){ var len = $("#pwd").val().length; if(len==0){ $("#pwderror").html("密码不能为空!"); $("#loginfrm").attr("onsubmit","return false"); } }) }) function check(){ fr=document.form1; if(fr.phone_mobile.value==""){ fr.phone_mobile.focus(); return false; } if((fr.login_password.value!="")){ fr.pwd1.focus(); return false; } fr.submit(); } </script> <body> <div class="page-container"> <h1>登录</h1> <form name="form1" id="loginfrm" action="userlogin.action" method="post" onsubmit=""> 手机号:<input type="text" name="phone_mobile" id="phone_number"><span style="color: red;" id="usernameerror"></span><br> 密 码:<input type="password" name="login_password" id="pwd" ><span style="color: red;" id="pwderror"></span> <button type="submit" class="submit_button" onclick="return check()">登录</button> </form> <br><br><br> <h2><a href="pages/register.jsp">注册</a></h2> </div> </body> </html>
以下是注册界面
<!doctype html public "-//w3c//dtd html 4.01 transitional//en"> <html> <head> <base href="<%=basepath%>"> <title>用户注册</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <link rel="stylesheet" href="assets/css/style.css"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <script type="text/javascript" src="<%=basepath%>/js/jquery-1.8.3.js"></script> <script src="<%=basepath%>/js/my97datepicker/wdatepicker.js" ></script> <script type="text/javascript"> // 用户名合法性的判断 $(function(){ $("#phone_number").blur(function(){ var phone = $("#phone_number").val(); var len = $("#phone_number").val().length; $.getjson("userjudge.action",{"phone_mobile":phone},function(data){ if(data!=null){ alert("手机号已注册,青重新输入!!"); $("#usernameerror").html("手机号已注册!"); $("#regfrm").attr("onsubmit","return false"); }else if(len==0||phone==null){ $("#usernameerror").html("手机号不能为空!"); $("#regfrm").attr("onsubmit","return false"); } else if (!checkcontactnumber()) { $("#usernameerror").html("不符合手机号格式!"); $("#regfrm").attr("onsubmit","return false"); } else{ $("#usernameerror").html("恭喜!手机号可用!") $("#regfrm").attr("onsubmit","return true"); } }); }); }); // 密码合法性的判断 $(function(){ $("#pwd").blur(function(){ var len = $("#pwd").val().length; if(len==0){ $("#pwderror").html("密码不能为空!"); $("#regfrm").attr("onsubmit","return false"); } if(len>0&&len<6){ $("#pwderror").html("密码位数最少为6位!"); $("#regfrm").attr("onsubmit","return false"); } if(len>=6){ $("#pwderror").html("密码格式正确!"); $("#regfrm").attr("onsubmit","return true"); } }) }) // 确认两次密码 $(function(){ $("#conpwd").blur(function(){ var oldpwd = $("#pwd").val(); var conpwd = $("#conpwd").val(); var number = $("#conpwd").val().length; if(number == 0){ $("#pwderror").html("密码不能为空!"); $("#regfrm").attr("onsubmit","return false"); } else if(oldpwd!=conpwd){ $("#conpwderror").html("两次密码不一致!"); $("#regfrm").attr("onsubmit","return false"); }else{ $("#conpwderror").html("密码符合!"); $("#regfrm").attr("onsubmit","return true"); } }) }) function check(){ fr=document.reg; if(fr.phone_mobile.value==""){ fr.phone_mobile.focus(); return false; } if((fr.login_password.value=="")){ fr.login_password.focus(); return false; } if((fr.login_password2.value=="")){ fr.login_password2.focus(); return false; } fr.submit(); } function checkcontactnumber() { var mobile = $.trim($("#phone_number").val()); var ismobile = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})|(14[0-9]{1}))+\d{8})$/; if (!ismobile.exec(mobile) && mobile.length != 11) { $("#phone_number").focus(); return false; } return true; } </script> <body> <!-- <form id="regfrm" action="userreg.action" method="post" onsubmit=""> 用户名:<input type="text" name="username" id="uname"><span style="color: red;" id="usernameerror"></span><br/> 密码:<input type="password" name="password" id="pwd"><span style="color: red;" id="pwderror"></span><br/> 确认密码:<input type="password" id="conpwd"><span style="color: red;" id="conpwderror"></span><br/> 生日<input type="text" name="birthday" onclick="wdatepicker()" class="wdate"><br/> <input type="submit" value="注册"> </form> --> <div class="page-container"> <h1>用户注册</h1> <!-- <form id="regfrm" action="userreg.action" method="post" onsubmit=""> 用户名:<input type="text" name="username" class="username" > 密 码:<input type="password" name="password" class="password" > <button type="submit" class="submit_button">登录</button> --> <form name="reg" id="regfrm" action="userreg.action" method="post" onsubmit=""> 手机号:<input type="text" name="phone_mobile" id="phone_number"><span style="color: red;" id="usernameerror"></span><br/> 密码:<input type="password" name="login_password" id="pwd"><span style="color: red;" id="pwderror"></span><br/> 确认密码:<input type="password" name="login_password2" id="conpwd"><span style="color: red;" id="conpwderror"></span><br/> <button type="submit" class="submit_button" onclick="return check()">注册</button> </form> </div> </body> </html>
页面中对手机号进行了验证,而且能够与后台进行交互,判断数据库中是否已有此手机号,页面所需的js文件和css配置会在以下给出,
进入正题
数据库中包含用户手机号,用户密码,以及注册信息,和生成的唯一识别码
以下是用户的实体类
package com.register.vo; import java.util.date; public class user { private int id; private string phone_mobile;//用户手机号 private string login_password;//用户登录密码 private date register_time;//用户注册日期 private string user_code;//用户唯一识别id public user(int id, string phone_mobile, string login_password, date register_time, string user_code) { super(); this.id = id; this.phone_mobile = phone_mobile; this.login_password = login_password; this.register_time = register_time; this.user_code = user_code; } public user(string phone_mobile, string login_password, date register_time, string user_code) { super(); this.phone_mobile = phone_mobile; this.login_password = login_password; this.register_time = register_time; this.user_code = user_code; } public user() { } public int getid() { return id; } //对用户数据进行封装 public void setid(int id) { this.id = id; } public string getphone_mobile() { return phone_mobile; } public void setphone_mobile(string phone_mobile) { this.phone_mobile = phone_mobile; } public string getlogin_password() { return login_password; } public void setlogin_password(string login_password) { this.login_password = login_password; } public date getregister_time() { return register_time; } public void setregister_time(date register_time) { this.register_time = register_time; } public string getuser_code() { return user_code; } public void setuser_code(string user_code) { this.user_code = user_code; } }
下面这一步是比较重要的一步,controller类, 如下所示
package com.register.controller; import java.net.inetaddress; import java.net.unknownhostexception; import java.text.dateformat; import java.text.simpledateformat; import java.util.date; import java.util.hashmap; import java.util.map; import java.util.uuid; import java.util.regex.matcher; import java.util.regex.pattern; import javax.script.scriptengine; import javax.script.scriptenginemanager; import javax.script.scriptexception; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpsession; import org.apache.ibatis.session.sqlsession; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.controller; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.responsebody; import com.register.service.userservice; import com.register.vo.user; //让控制器成为一个bean @controller //这个控制器是接受user_reg页面传过来的参数去操作数据库 public class usercontroller { @autowired private sqlsession sqlsession; @autowired private userservice us; @autowired private httpservletrequest req; @requestmapping("/userreg.action") //jsp页面通过userreg.action找到这个方法 public string userreg(user user){ map<string,object> map = new hashmap<string, object>(); map.put("phone_mobile", user.getphone_mobile()); map.put("login_password", user.getlogin_password()); //判断页面传回的数据要求 pattern pattern = pattern.compile("^((13[0-9])|(15[^4,\\d])|(18[01236789]))\\d{8}$"); matcher matcher = pattern.matcher(user.getphone_mobile()); if(user.getphone_mobile()==null || user.getlogin_password()==null || !matcher.matches()){ return "index.jsp"; } //获取当前注册时间 date date = new date(); dateformat df = new simpledateformat("yyyy-mm-dd hh:mm:ss"); map.put("register_time", df.format(date)); //生成唯一识别码 string s = uuid.randomuuid().tostring(); string user_code = s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24); map.put("user_code", user_code); //将数据添加到数据库中 int a = sqlsession.insert("com.register.dao.adduser",map); req.setattribute("phone_mobile", user.getphone_mobile()); req.setattribute("login_password", user.getlogin_password()); return "pages/register_success.jsp"; } //处理用户名唯一性的判断 @requestmapping("/userjudge.action") @responsebody public user userjudge(string phone_mobile) { user u = sqlsession.selectone("com.register.dao.judgeuser",phone_mobile); system.out.println(u.getphone_mobile()); return u; } //用户登录的判断 @requestmapping("/userlogin.action") public string userlogin(string phone_mobile,string login_password){ //对页面传回的值进行二次判断 pattern pattern = pattern.compile("^((13[0-9])|(15[^4,\\d])|(18[01236789]))\\d{8}$"); matcher matcher = pattern.matcher(phone_mobile); if(phone_mobile==null || login_password==null || !matcher.matches()){ return "pages/user-login-no.jsp"; } user u = us.userlogin(phone_mobile, login_password); //查到用户了,执行登录成功的操作 if(u!=null){ req.getsession().setattribute("u", u); return "pages/user-login-ok.jsp"; }else{ return "pages/user-login-no.jsp"; } } //用户退出销毁session 跳转到登录页 @requestmapping("/userexit.action") public string userexit(httpsession session){ session.invalidate(); return "index.jsp"; } }
userservice类:
package com.register.service; import java.util.hashmap; import java.util.map; import org.apache.ibatis.session.sqlsession; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.service; import com.register.vo.user; @service public class userservice { @autowired private sqlsession sqlsession; public user userlogin(string phone_mobile,string login_password){ map<string,object> map = new hashmap<string, object>(); map.put("phone_mobile",phone_mobile); map.put("login_password", login_password); user u = sqlsession.selectone("com.register.dao.userlogin",map); return u; } }
注入测试类:
package com.register.util; import org.springframework.stereotype.controller; @controller public class testutil { public void a(){ system.out.println("注入成功!"); } }
ok,到这里已经基本差不多了,但是这里边所给的代码并不完整,为了方便大家相互交流学习,这是源码以及数据库文件,
链接:注册登录功能,想要参考源码的可以自己下载。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: Java的数据类型和参数传递(详解)