Spring MVC+mybatis實現(xiàn)注冊登錄功能
本文實例為大家分享了Spring MVC mybatis實現(xiàn)注冊登錄功能的具體代碼,供大家參考,具體內(nèi)容如下
前期準備:
如下圖所示,準備好所需要的包

新建工程,導(dǎo)入所需要的包,在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的優(yōu)先級,這個數(shù)字只能整數(shù),正整數(shù)才會初始化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>
<!-- 導(dǎo)入數(shù)據(jù)庫配置文件 -->
<util:properties id="myproperties" location="/WEB-INF/config/jdbc.properties">
</util:properties>
<!-- 創(chuàng)建數(shù)據(jù)庫連接池 -->
<bean id="ds" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 定義數(shù)據(jù)庫連接的參數(shù) -->
<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>
<!-- 數(shù)據(jù)庫連接池的兩個屬性 -->
<property name="initialPoolSize" value="3"></property>
<property name="maxPoolSize" value="20"></property>
</bean>
<!-- 替代mybatis的配置文件用來執(zhí)行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>
配置好數(shù)據(jù)庫信息
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/cheshangbao?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useOldAliasMetadataBehavior=true username=root password=admin
另外,還有所需要的操作數(shù)據(jù)庫的語句:
<?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("密碼位數(shù)最少為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>頁面中對手機號進行了驗證,而且能夠與后臺進行交互,判斷數(shù)據(jù)庫中是否已有此手機號,頁面所需的js文件和css配置會在以下給出,
進入正題
數(shù)據(jù)庫中包含用戶手機號,用戶密碼,以及注冊信息,和生成的唯一識別碼
以下是用戶的實體類
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;
}
//對用戶數(shù)據(jù)進行封裝
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頁面?zhèn)鬟^來的參數(shù)去操作數(shù)據(jù)庫
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());
//判斷頁面?zhèn)骰氐臄?shù)據(jù)要求
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);
//將數(shù)據(jù)添加到數(shù)據(jù)庫中
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){
//對頁面?zhèn)骰氐闹颠M行二次判斷
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);
//查到用戶了,執(zhí)行登錄成功的操作
if(u!=null){
req.getSession().setAttribute("u", u);
return "pages/user-login-ok.jsp";
}else{
return "pages/user-login-no.jsp";
}
}
//用戶退出銷毀session 跳轉(zhuǎn)到登錄頁
@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,到這里已經(jīng)基本差不多了,但是這里邊所給的代碼并不完整,為了方便大家相互交流學(xué)習(xí),這是源碼以及數(shù)據(jù)庫文件,
鏈接:注冊登錄功能,想要參考源碼的可以自己下載。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
ConditionalOnProperty注解的作用和使用方式
在SpringBoot項目開發(fā)中,@ConditionalOnProperty注解允許根據(jù)配置文件中的屬性值來控制配置類是否生效,該注解通過屬性name和havingValue來判斷配置是否注入,如果application.properties中的對應(yīng)屬性值為空或不匹配havingValue設(shè)定值2024-09-09
Java實現(xiàn)前端jsencrypt.js加密后端解密的示例代碼
這篇文章主要為大家詳細介紹了如何利用jsencrypt.js實現(xiàn)前端加密,利用Java實現(xiàn)后端解密的功能,文中的示例代碼講解詳細,需要的可以參考一下2022-09-09
JDK8新特性-java.util.function-Function接口使用
這篇文章主要介紹了JDK8新特性-java.util.function-Function接口使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04
Python實現(xiàn)filter函數(shù)實現(xiàn)字符串切分
這篇文章主要介紹了Python實現(xiàn)filter函數(shù)實現(xiàn)字符串切分,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-03-03

